4

I need to find the position of the first element of a list that is either greater than zero (or some other criterion) or a symbol.

Something like

 lst={0,0,k,1,4}

and as result

 position = 3

If there was no symbol the following command would do the job

 First[Flatten[Position[lst, _?(Abs[#] > 0 &)]]]

If I add || MatchQ[_Symbol] the answer will always be zero.

Many thanks

whuber
  • 20,544
  • 2
  • 59
  • 111
Ed Mendes
  • 618
  • 5
  • 11

3 Answers3

7

I misread the question. Assuming I now understand you just want:

lst = {0, 0, k, 1, 4}

Position[lst, _?Positive | _Symbol, 1, 1, Heads -> False][[1, 1]]
3

My misreading was itself an interesting problem. I thought you wanted the position of the first positive value as if the symbols were not in the list. For example:

lst = {b, 0, k, 0, 1, 4}

Position[
 Cases[lst, _?NumericQ],
 _?Positive, 1, 1
][[1, 1]]
3

because 1 is at position three in {0, 0, 1, 4}.

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
7
 Position[lst, Except[0|0., _], {0, Infinity}, 1, Heads -> False][[1,1]]

or

 Cases[lst, {zeros : (0|0.) ..., Except[0|0.], ___} :> 1 + Length[{zeros}], {0}][[1]]

or

 Length@First@Split[lst, #1 == 0 &]

or

 1 + LengthWhile[lst, # == 0 &]

all give 3.

kglr
  • 394,356
  • 18
  • 477
  • 896
  • I just realized that I misunderstood the question. Oops. – Mr.Wizard Jan 14 '13 at 13:23
  • I'm a bit confused by your code. Why are you looking at levels down to Infinity in the first line? Why are you assuming that the only non-negative numbers are 0? Maybe I still don't understand the question. – Mr.Wizard Jan 14 '13 at 13:31
  • @kguler - Many thanks, however there is a problem if one has 0. instead of 0 for the first two options. Third works great. Many thanks. – Ed Mendes Jan 14 '13 at 13:32
  • @EdMendes, excellent point.. will fix in a moment. – kglr Jan 14 '13 at 13:38
  • 1
    @Mr.W, {0,Inifinity} is my "instinctive default" levelspec ; it is not necessary in this case, 1 or {1} sufficient. Regarding "the only non-negative numbers..", I was going with the condition _?(Abs[#] > 0 &) in Ed's code. – kglr Jan 14 '13 at 13:52
  • @kguler - Again thank you ever so much. Would you be so kind to give details on each function, please? I am sort of newbie and Mathematica codes still baffle me. – Ed Mendes Jan 14 '13 at 14:57
  • @Ed, I will add some annotations later today. – kglr Jan 14 '13 at 16:27
  • @kuler - Great! Many thanks. – Ed Mendes Jan 15 '13 at 01:42
1

Using SequencePosition (introduced in 2015 with V 10.1)

list = {0, 0, k, 1, 4};

SequencePosition[list, {0, Except[0]}][[1, 2]]

gives

3
eldo
  • 67,911
  • 5
  • 60
  • 168