9
$\begingroup$

There are two lists{2,5,9,...} and {natural numbers}. I need to compare it with natural numbers and get a list with 0 and 1 if the number is present in the list, to get {0,1,0,0,1,0,0,0,1,..}

$\endgroup$
4
  • 5
    $\begingroup$ Question is not clear. Can you give the short list you have and desired output? $\endgroup$ May 2 '18 at 12:36
  • $\begingroup$ All natural numbers? $\endgroup$
    – Kuba
    May 2 '18 at 13:36
  • 3
    $\begingroup$ @Kuba: Are you saying that your computer doesn't have $\aleph_0$ bytes of memory? $\endgroup$ May 2 '18 at 18:04
  • $\begingroup$ @MichaelSeifert :) I was concerned about the case where the first list contains integers outside of range of the second one. $\endgroup$
    – Kuba
    May 2 '18 at 18:19
17
$\begingroup$

Use SparseArray.

SparseArray[List /@ {2, 5, 9} -> 1] // Normal
(* {0, 1, 0, 0, 1, 0, 0, 0, 1} *)
$\endgroup$
1
  • 1
    $\begingroup$ This is brilliant! I would not have thought of that. $\endgroup$
    – MarcoB
    May 2 '18 at 14:21
7
$\begingroup$
list = {2,5,9,20};
res = ConstantArray[0, Last[list]] (* replace Last by Max if list is not ordered *)
res[[list]] = 1;
res
{0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}
$\endgroup$
1
  • $\begingroup$ You could also use ReplacePart, to avoid mutating data. But your approach is probably shorter. $\endgroup$
    – Szabolcs
    May 2 '18 at 13:19
5
$\begingroup$

How about this? A little verbose...

list = {2, 5, 9, 10, 119};
checklist[list_List] := Boole /@ (MemberQ[list, #] & /@ Range[Max[list]])
checklist@list

{0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}

Edit:

Another one, just for fun:

CoefficientList[Plus @@ ((x^#) & /@ list), x]
$\endgroup$
1
  • 2
    $\begingroup$ That last one is just silly. Kudos. $\endgroup$ May 2 '18 at 18:03
2
$\begingroup$
list = {2, 5, 9};
checklist = RandomInteger[{0, 10}, 10]
(*{9, 0, 2, 2, 0, 0, 8, 7, 0, 4}*)

Map[(If[MemberQ[list, #], 1, 0]) &, checklist]
(*{1, 0, 1, 1, 0, 0, 0, 0, 0, 0}*)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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