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.
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
.
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.
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}
*)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With