Message Boards Message Boards

0
|
2181 Views
|
2 Replies
|
3 Total Likes
View groups...
Share
Share this post:

Divisible with Select and Replace

Posted 4 years ago

Hello. I was trying to use the Divisible function along with the select and Replace function: Select[rn,Divisible[rn,3] ] (rn being a list), but it doesn't give any output. There is output when I do Select[rn, EvenQ] though, so I was confused as to whether Divisible doesn't work with Select or if I was making a syntax or other error? Additionally, on using the Replace function with the select and evenQ Replace[Select[rn, EvenQ] -> "even"][Select[rn, EvenQ]], the output is simply "even" for the whole list - it doesn't replace the even numbers within the list with "even." I also tried this with Replace[Select[rn, EvenQ] -> "even"][rn] but the output then was the list only. I was wondering if the Replace function works with the individual characters in a list? Any help would be appreciated. Thanks!

POSTED BY: Aadya Goel
2 Replies
Posted 4 years ago

If you want to use Select, the second argument must be a function. For example:

Select[Range[0, 100], Divisible[#, 3] &]

returns:

{0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, \
54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99}
POSTED BY: Mike Besso
Posted 4 years ago

Try

v={1,2,3,4,5,6};
d3[n_]:=Divisible[n,3];
Select[v,d3]

which returns

{3, 6}

Since the function d3 only accepts a single argument and returns True or False, just like EvenQ, that makes it possible for Select to understand that it is to pass each member of the list to the function, one at a time, so that the individual items can be tested.

Then try

v/.x_/;EvenQ[x]->even

or

ReplaceAll[v,x_/;EvenQ[x]->even]

which are exactly the same thing and which return

{1, even, 3, even, 5, even}

You can look up /; which is also called Condition in the help system. Those last two examples are going to replace every item in the list v, just as long as the item satisfies the condition of being even, with the word even.

POSTED BY: Bill Nelson
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