2
$\begingroup$

I have some expressions containing Kets, like

|1> + Sqrt[6] |3>

where the kets are created using [esc]ket[esc]. How can I find the largest number inside a ket? For example I would expect:

LargestN[|1> + Sqrt[6] |3>] = 3

At the moment I am doing it through matching regular expressions in the FullForm:

LargestN[state_] := Max[ToExpression /@ (StringReplace[#, 
   RegularExpression@"\\D" -> ""] & /@ 
 StringCases[state // FullForm // ToString, 
  RegularExpression@"Operator\[ket, \\d+\]"])]

While this does work, does anyone know a nicer way to do this?

Edit: Just in case someone stumbles across this in the future and gets confused, my code above won't work for you as I had another package loaded that was causing kets to be represented as

Operator[ket, n]

rather than the conventional

Ket[n]
$\endgroup$
6
$\begingroup$
expr= Ket[1] + Sqrt[6] Ket[3]

Max@Cases[expr, Ket[a_] -> a, Infinity]

3

$\endgroup$
  • $\begingroup$ Ignore my previous comment, I had another package loaded which was messing things up. $\endgroup$ – Ruvi Lecamwasam Oct 15 '15 at 10:30
  • 1
    $\begingroup$ @RuviLecamwasam Of course, this should work also if you use the form Operator[ket,n] but you have to replace Ket[a_]->a with Operator[ket,a_]->a. $\endgroup$ – SquareOne Oct 15 '15 at 12:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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