2
$\begingroup$

I want to add and subtract 3 from a list.

pos = {82,84}

If[# > 3,
       (# - 3) && (# + 3)] & /@ pos

the output I want:

{79,85,81,87}

the output I get:

{79 && 85, 81 && 87}
$\endgroup$
3
  • 1
    $\begingroup$ && is the same as And; you might want to use List, followed by Sequence instead. $\endgroup$ Aug 8 '20 at 8:58
  • 1
    $\begingroup$ {#-3,#+3}&/@pos//Flatten $\endgroup$
    – Artes
    Aug 8 '20 at 9:01
  • 1
    $\begingroup$ What do you want to happen if x <=3? Leave it there unmodified, or remove it from the list? If the first possibility, maybe {1,2,3,82,85} /. x_ /; x > 3 -> {x-3,x+3}//Flatten $\endgroup$
    – user1066
    Aug 8 '20 at 9:37
3
$\begingroup$
(* erase <=3 *)  
pos={1,2,3,82,84};
Cases[pos, x_?(# > 3 &) :> {x - 3, x + 3}] // Flatten


(* keep <=3 *)
pos={1,2,3,82,84};
pos /. x_?(# > 3 &) :> {x - 3, x + 3} // Flatten
$\endgroup$
1
$\begingroup$

Answer suggested by [b.gates.you.know.what][1]

ifs = If[# > 3,
List[Sequence[# - 3, # + 3]]] & /@ pos

It works!! [1]: https://mathematica.stackexchange.com/users/134/b-gates-you-know-what

$\endgroup$
1
  • 1
    $\begingroup$ This gives a lot of extraneous stuff in the output. $\endgroup$ Aug 8 '20 at 18:14
-2
$\begingroup$
Split[{79, 85, 81, 87}, 
 Abs[#1 - #2] == 6 || Abs[#1 - #2] == 3 || Abs[#1 - #2] == 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.