4
$\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
    Nov 9, 2023 at 9:48

6 Answers 6

8
$\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$
5
$\begingroup$
UniqueElements[{set1,{ -1/x}}][[1]]

(* {-x^(-1)+x/2-2*Log[x]-Log[x]/x,1} *)
$\endgroup$
5
$\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$
3
$\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$
3
$\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$
2
$\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

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.