5
$\begingroup$

Is there simpler and/or faster code for this?

List1={1,2,4,6,7};
List2={1,3,5,6,7};

Rule: If values at respective positions match, output 1 else output 0.

Result:

{1,0,0,1,1}

$\endgroup$
0

6 Answers 6

10
$\begingroup$
ClearAll[f]
f = 1 - Unitize[# - #2] &;


f[List1, List2]
{1, 0, 0, 1, 1}
$\endgroup$
1
  • 3
    $\begingroup$ @Reda.Kebbaj, using NonDairyNeutrino's test input it is about 20x faster than 1-Boole[Negative[-Abs[List1 -List2]]]. Have not tested it against ResourceFunction["BoolEval"] (somehow I cannot download it on my machine). $\endgroup$
    – kglr
    May 10, 2023 at 21:23
7
$\begingroup$

Not very efficient, but perhaps 'simpler':

KroneckerDelta@@@Transpose[{List1,List2}]

(* {1, 0, 0, 1, 1} *)

Or

MapThread[KroneckerDelta,{List1,List2}]

(* {1, 0, 0, 1, 1} *)
$\endgroup$
6
$\begingroup$
List1 = {1, 2, 4, 6, 7};
List2 = {1, 3, 5, 6, 7};
Boole@*SameQ @@@ Transpose[{List1, List2}]

{1, 0, 0, 1, 1}

$\endgroup$
6
$\begingroup$

Another approach:

list1 = {1, 2, 4, 6, 7};
list2 = {1, 3, 5, 6, 7};
1 - Mod[Sign[list2 - list1], 2]

{1, 0, 0, 1, 1}
$\endgroup$
2
  • 1
    $\begingroup$ I believe you wanted to write Mod[Sign[list2 - list1 - 1], 2]? $\endgroup$
    – Syed
    May 11, 2023 at 2:16
  • $\begingroup$ @Syed -- I moved the "1" around incorrectly... sorry about that $\endgroup$
    – bill s
    May 11, 2023 at 2:39
5
$\begingroup$

Maybe something from one of our own

list[1] = RandomReal[{0,1},10^6];
list[2] = list[1] + SparseArray[{i_?EvenQ} :> RandomReal[{0,1}], 10^6];

ResourceFunction["BoolEval"][list[1] == list[2]] // Log10@*First@*RepeatedTiming

-8.07827

$\endgroup$
1
  • $\begingroup$ I second BoolEval, it is a very useful and fast toolkit. $\endgroup$ May 12, 2023 at 11:08
4
$\begingroup$

I code this, but I need more speed.

List1={1,2,4,6,7};List2={1,3,5,6,7}; 
1-Boole[Negative[-Abs[List1 -List2]]]
$\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.