Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mathematica Pick stop a list as soon as I get a 3

Here's what I have...

Select[roll, # <= 3 &]

Now, the list that follows may have one 3 or two three's. I want it to stop at the first three from left to right.

Mathematician trying to code.

like image 954
Corshot Avatar asked Apr 01 '11 21:04

Corshot


3 Answers

Note: I removed my original posting, which was basically like that of belisarius. Here's another try...

If you are sure that the number 3 is a member of roll then this should work:

TakeWhile[roll, # != 3 &]~Append~3

This is equivalent to:

Take[roll, LengthWhile[roll, # != 3 &] +1]

If you cannot make this assumption, just test first with MemberQ

EDIT: Credit goes to TomD for suggesting the +1 in the second solution, which eliminates the need to use Append.

like image 103
DavidC Avatar answered Nov 20 '22 07:11

DavidC


This is an order of magnitude faster than TakeWhile on a list of integers.

list /. {x___, 3, ___} :> {x}

To get the list through 3, just use {x, 3} on the right hand side.

like image 6
Mr.Wizard Avatar answered Nov 20 '22 07:11

Mr.Wizard


You could try something like:

f[list_, item_] := list[[1 ;; Position[list, item][[1, 1]]]]  

Usage:

f[{1, 2, 3, 4, 1, 4, 3, 4, 3, 5, 6, 7, 3, 2}, 3]
(*
->{1,2,3}
*)
f[{1, 2, 3, 4, 1, 4, 3, 4, 3, 5, 6, 7, 3, 2}, 5]
(*
->{1,2,3,4,1,4,3,4,3,5}
*)

If you also want to filter values greater than 3, you may just use your code wrapping mine:

g[list_, item_] :=  Select[list[[1 ;; Position[list, item][[1, 1]]]], # <= 3 &]  

so:

g[{-1, 1, 2, 5, 7, 1, 3, 4, 1, 4, 3, 4, 3, 5, 6, 7, 3, 2}, 3]
(*
->{-1,1,2,1,3}
*)
like image 1
Dr. belisarius Avatar answered Nov 20 '22 05:11

Dr. belisarius