3
$\begingroup$

Consider a toy list

l = {x[2],x[32],x[43],x[56],x[72]};

I would like to find the position of the first element within this list, for which x[y] is such that y>N where N is a positive integer that I will specify. In case if N is bigger than any label of any x[y], then the result should be zero. So for example:

getPos[l,35]

3

getPos[l,60]

5

getPos[l,80]

0

How can I do that in an efficient manner?

$\endgroup$
2
  • 2
    $\begingroup$ Maybe I don't understand the question but FirstPosition? $\endgroup$
    – unlikely
    Feb 22, 2016 at 23:10
  • $\begingroup$ Beware of things like x[n_] := 3; l = {x[2],x[32],x[43],x[56],x[72]}; $\endgroup$ Feb 22, 2016 at 23:13

2 Answers 2

7
$\begingroup$

For default you can use third arg as in

p[n_] := First@FirstPosition[l, x[k_] /; k >= n, {0}]
$\endgroup$
0
$\begingroup$

Thanks to a comment by unlikely here is the solution:

getPos[l_List,myN_Integer]:=FirstPosition[l,x[qq_Integer] /; qq > myN,{0}][[1]]
$\endgroup$
2
  • 1
    $\begingroup$ Better to use n than N. $\endgroup$
    – bbgodfrey
    Feb 22, 2016 at 23:16
  • $\begingroup$ Fixed it to something that starts with a lower case letter. $\endgroup$
    – Kagaratsch
    Feb 22, 2016 at 23:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.