# Finding where a specific number appears in an expression

I would like to see how many times (and where) the number "91" appear in a set of formulae.

I thought of using Position[expr , 91 , Infinity], but it seems not to be working in this simple example:

Position[{Log[Sqrt[1 + I Sqrt[-1 + (4 mm)/91]]]}, 91, ∞]


which gives

{}

Why?

• At first glance this feels like it could be a bug. Report to WRI Support to see what they say. – Edmund Feb 21 '19 at 12:22
• @Edmund. If you look at the FullForm of this expression, the 91 is embedded inside Rational[4,91], and it seems like the pattern matcher is treating anything that looks like Rational[_,_] as atomic (which might or might not be intended behavior). Indeed: Cases[Rational[4, 91], 91, Infinity] evaluates to {}. The work-around of Alexei's below is a reasonable hack, although annoying that it must be done. – march Feb 21 '19 at 18:11
• Interestingly, Cases[Rational[x, 91], 91, Infinity] evaluates to {91}, indicating that the pattern matcher sees actual numbers in the form Rational[_, _] as atomic, but if the expression is symbolic, it does not. – march Feb 21 '19 at 18:15
• @march. Rational[x, 91] is not an atomic expression, so it is treated differently from Rational[4, 91] which is atomic. – m_goldberg Feb 21 '19 at 22:10

Try this:

expr = Log[Sqrt[1 + I Sqrt[-1 + (4 mm)/91]]];
Position[expr, f_[x_, 91] | f_[91, x_]]

(*  {{1, 1, 2, 2, 1, 2, 1}}   *)


Have fun!

expr = {Log[Sqrt[1 + I Sqrt[-1 + (4 mm)/91]]]};


If you look at the FullForm of the expression, you see that 91 appears only inside Rational

expr // FullForm


Since Rational is an atomic element (Atomic Elements of Expressions), the 91 is not accessible by Position. However, you can see the position of the Rational containing 91 as shown by Alexei.

Position[expr, Rational[_, 91], ∞]

(* {{1, 1, 1, 2, 2, 1, 2, 1}} *)


There are no parts to an atomic expression.

Rational[4, 91][[-1]]


An alternative pattern to search through the atoms:

Position[Log[Sqrt[1 + I Sqrt[-1 + (4 mm)/91]]], _?AtomQ[___, 91, ___] | 91]


{{1, 1, 2, 2, 1, 2, 1}}

Also

Position[Log[Sqrt[1 + I Sqrt[-1 + (4 mm)/91]]],
TypeSystem\$AtomPattern[___, 91, ___] | 91]


{{1, 1, 2, 2, 1, 2, 1}}

Another approach would be to change the expression into a string and then locate the string "91" within that. For your example:

expr = {Log[Sqrt[1 + I Sqrt[-1 + (4 mm)/91]]]};
StringPosition[ToString[expr], "91"]
{{94, 95}}


Which shows that 91 occurs in the final two positions of the string.

• While this works, it's rather counter-intuitive that 9 and 1 are the final two characters in the string for that expression. A naive expectation might be that ] and }` would be the final two characters. – High Performance Mark Feb 21 '19 at 17:26
• Counterintuitive or not... StringLength[ToString[expr]] is 95. – bill s Feb 21 '19 at 21:30