Applying Mod on list of list with outcomes +1, -1, other

3

1

I have a list

lis = {{7, 8}, {17, 9}, {11, 10}, {12,10}}

I want to apply Mod to each pair with output +1,-1 or other. I should get

lis2 = {-1, -1, 1, other}

I tried

Apply[Mod, lis, {1}]

but that just gives me all positive remainders.

user57467

Posted 2019-12-24T16:00:55.100

Reputation: 1 598

3Have Mod start at -1: `In[397]:= lis = {{7, 8}, {17, 9}, {11, 10}, {12, 10}} Replace[Apply[Mod[##, -1] &, lis, {1}], a_ /; Abs[a] =!= 1 :> "other", {1}]

Out[397]= {{7, 8}, {17, 9}, {11, 10}, {12, 10}}

Out[398]= {-1, -1, 1, "other"}` – Daniel Lichtblau – 2019-12-24T16:13:01.417

Answers

6

You can use -1 as the third argument of Mod:

Mod[##, -1] & @@@ lis 

{-1, -1, 1, 2}

and replace integers other than -1 and 1 with "other":

% /. Except[-1 | 1, _Integer] -> "other"

{-1, -1, 1, "other"}

or combine the two steps:

Mod[##, -1] & @@@ lis /. Except[-1 | 1, _Integer] -> "other"

{-1, -1, 1, "other"}

kglr

Posted 2019-12-24T16:00:55.100

Reputation: 302 076

2A little cleaner: Mod[##, -1] /. Except[-1 | 1] -> "other" & @@@ lis – Mr.Wizard – 2019-12-24T23:51:57.303

Great! I understand. And how would you write Mod[##, -1] & @@@ lis in the Apply format? – user57467 – 2019-12-26T12:43:50.080

@user57467, you can use Apply[Mod[##, -1] &, lis, {1}]. – kglr – 2019-12-26T15:41:06.993

5

lis = {{7, 8}, {17, 9}, {11, 10}, {12, 10}};

To Apply Mod you would need to include the level specification

Apply[Mod, lis, {1}]

(* {7, 8, 1, 2} *)

or the abbreviated form

Mod @@@ lis

(* {7, 8, 1, 2} *)

Or to get the desired results

Module[{m = Mod @@ #}, 
   If[m == (#[[2]] - 1), -1, If[m == 1, 1, "other"]]] & /@ lis

(* {-1, -1, 1, "other"} *)

Bob Hanlon

Posted 2019-12-24T16:00:55.100

Reputation: 95 281

Wow! Good! Thank you! – user57467 – 2019-12-24T16:24:25.080