3

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 ->?

Gravitino
  • 191
  • 6

2 Answers2

7

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

Boole@OddQ@Range[0, 6]
Alan
  • 13,686
  • 19
  • 38
7

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.

kglr
  • 394,356
  • 18
  • 477
  • 896