# Python3, 497 bytes ```lang-py lambda x:sum(f(x)) E=enumerate S=sorted u=lambda x:str(S(map(S,x))) def f(a,p=1): if len(a)==1:yield p*(a[0][0]==a[0][1]);return d={} for i,j in E(a): if j[0]!=j[-1]:n=u(a[:i]+a[i+1:]);d[(n,0)]=d.get((n,0),0)+1 for I,J in E(a): if i<I: F=[y for x,y in E(a)if x not in[i,I]] for j in[j,j[::-1]]: for J in[J,J[::-1]]: if j[-1]!=J[0]:n=u(F+[j[:-1]+J[1:]]);d[(n,1)]=d.get((n,1),0)+1 if{}==d:yield p for x,y in d: if y:yield from f(eval(x),p*(d[(x,y)]/sum(d.values()))) ``` [Try it online!](https://tio.run/##fVHBbuMgFLzzFfQGNe2WppVWdDk2UnzNkUUVFbiLZWOL4CpW1W/PPpxGTSS7EgfevHnzBqYf078urH738bCWfw@NaV@twXuxG1pSkT2l6Fm6MLQumuTQVu66mJxFg/xmpki2pDU92TLgU2RdhStiWC85FQj7CjcuEEOl5GL0rrG4vyZG3Wk4Uk4XrulTdGmIAWErPz4RrrqIPauxD/gZZkEnC9VAvpK1uuFaBDmAivC6MMoXXICEVSSwO6qlvX1ziUwFnILDdBbcsPJcMCv6P5vpitdSjRNpz8YTCfp7HLoEtfJso/XEzKRsTNWsVkKAF32UmDp5gypZedk5mgfgSpbwhsn8ulAwD1hRKrB/8s/P/fOTf199fEppTx@Izq3ar98Zv7pV7FpIwL2bBhJk8NsgDFyqf@VY7S00BrcjEBY95LRS99KQhopjBAre6vVFAA3N5UsuoglvjtRUoz76kMiaTNNK5@gvIT6D3c/xGObz8AJ7NQ8/zMOPczbmte/ntVeLK5c9Lm/4sfPDnsVV/Hvy8B8)