2

I read the doc about Position built-in function:

"Position[expr, pattern] gives a list of the positions at which objects matching pattern appear in expr."

For instance:

Position[{"a", "b", "A", "a", "B", "c", "b"}, "b"]

returns

{{2}, {7}}

However, I am desperately looking for a built-in function that works with a test instead of a pattern matching. To be clear I would like a built-in function that behaves as follow:

(* does not work, for illustration purpose *)
Position[{"a", "b", "A", "a", "B", "c", "b"},UpperCaseQ] 

would return:

{{3}, {5}}

I am aware of the Select function,

Select[{"a", "b", "A", "a", "B", "c", "b"}, UpperCaseQ]

but it returns values and not positions (and I want positions!):

{"A", "B"}

Question: Do I miss read the doc, maybe such built-in function exist?

Picaud Vincent
  • 2,463
  • 13
  • 20

3 Answers3

6

I just found this:

Position[{"a", "b", "A", "a", "B", "c", "b"}, _String?UpperCaseQ]

is working.


Update: Albert Retey, just rightly commented that it works without the head check.

For instance:

Position[Range[10], _?OddQ]

is working.

Picaud Vincent
  • 2,463
  • 13
  • 20
  • 1
    that's something along the lines of what I was going to suggest. :) – rcollyer Nov 20 '17 at 16:33
  • @rcollyer, thanks. On my side it was not on purpose. I was annoyed by this and just found the solution I posted. – Picaud Vincent Nov 20 '17 at 16:37
  • 1
    this would work equally well without the head-check, e.g.: Position[{0.,-1,5,-5.3},_?Negative]. That is probably just relevant for those cases where your entries do not all have the same head but I often use it without checking for the head, the typical test function would return false for non-matching entries anyway, cf.: OddQ["a"] – Albert Retey Nov 20 '17 at 21:35
  • @AlbertRetey thanks for the constructive comment, I have updated my answer. – Picaud Vincent Nov 20 '17 at 21:53
4
Position[UpperCaseQ /@ vars, True]
Alucard
  • 2,639
  • 13
  • 22
1

You could try something like this.

vars = {"a", "b", "A", "a", "B", "c", "b"};

Position[Table[UpperCaseQ[vars[[i]]], {i, Length[vars]}], True]

(*{{3},{5}}*)
Bob Brooks
  • 466
  • 2
  • 13