Message Boards Message Boards

0
|
3541 Views
|
5 Replies
|
2 Total Likes
View groups...
Share
Share this post:

A function gets two very similar arguments, how to make the code shorter?

Posted 2 years ago

I have the following two expressions that I pass to the Union function:

Position[Divisible[Range[10], 3], True]

and

Position[Divisible[Range[10], 5], True]

You can see that they are very similar (3 and 5 is the only difference).

My question is: can I make the following command shorter

Union[
 Position[Divisible[Range[10], 3], True]
 ,
 Position[Divisible[Range[10], 5], True]
 ]

?

POSTED BY: Ehud Behar
5 Replies
MapIndexed[{v, i} \[Function] 
  If[Divisible[v, 3] || Divisible[v, 5], i, Nothing], Range@10]
POSTED BY: Robert Nowak

Yet another way:

Position[Map[Mod[#, 3] Mod[#, 5] &, Range[10]], 0]
POSTED BY: Gianluca Gorni
Posted 2 years ago

Another way

If[Mod[#, 3] == 0 || Mod[#, 5] == 0, #, Nothing] & /@ Range@10
POSTED BY: Updating Name

Ehud,

I think this gives basically the same result:

Union@Flatten[Table[n, {n, #, 10, #}] & /@ {3, 5}]
(*  Out:   {3,5,6,9,10}  *)
POSTED BY: Henrik Schachner
Posted 2 years ago

Thanks a lot!

POSTED BY: Ehud Behar
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract