3
$\begingroup$

I am trying to define a substitution that gives 1 for odd numbers and 0 for even numbers. My guess was (in a particular example)

{0, 1, 2, 3, 4, 5, 6} /. N_Integer -> If[EvenQ[N], 0, 1]

But the output is {1,1,1,1,1,1,1}. The problem is in EvenQ[] which is acting on a symbol, but I specified before that it should be applied only to integers, so I do not understand why it does not work.

Where is the problem? Does it have something to do with ->?

$\endgroup$
  • 14
    $\begingroup$ Yes. Use :> instead of ->. But then, why not use Mod[list, 2]? $\endgroup$ – J. M.'s discontentment Oct 18 '18 at 13:25
7
$\begingroup$

In case speed matters Mod suggested by J.M. in comments is orders of magnitude faster than ReplaceAll and Boole:

SeedRandom[1]
input = RandomInteger[10^6, 10^6];
First[RepeatedTiming[res0 = input /. n_Integer :> If[EvenQ[n], 0, 1];]]

0.999

First[RepeatedTiming[ res1 = Boole@OddQ@input; ]]

.0226

First[RepeatedTiming[res2 =  With[{True = 1, False = 0}, Evaluate@OddQ[input]]; ]]

0.048

First[RepeatedTiming[ res3 = Mod[input, 2];]] 

0.00722

res0 == res1 == res2 == res3
> True

where the trick in res2 is from this answer by Mr.Wizard.

| improve this answer | |
$\endgroup$
  • $\begingroup$ Nice trick! (But it's disappointing.) $\endgroup$ – Alan Oct 19 '18 at 14:03
7
$\begingroup$

See JM's comment. The following points in a somewhat more general direction for some queries.

Boole@OddQ@Range[0, 6]
| improve this answer | |
$\endgroup$
  • 3
    $\begingroup$ It should be Boole@OddQ@Range[0, 6] $\endgroup$ – rmw Oct 18 '18 at 21:01

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