# 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/##bVHBbuMgEL3zFfQGa5ot7R5WtHNspPiaI4sqKnCKZWOL4FWsqt@eHZxGm0iRODBv3jwe88Y5fwzx6feYjmv4c@xs/@4sPaj91LOGHTgnr@Dj1Ptksydb2A8pe0cm@M/MiW1Zb0e2FcjnxPmGNsyKESRXhIaGdj4yywGkmoPvHB1/MKsfDB6A5SINf04@TykS6uDzi9BmSDSIloZIX3EWdYpQi@Q7aPW9NCrChCoqmMrqUEmFEk6zKB64Abfa@cyWAk8lcboIbkR9KVgUw8tmudI16HkhHcR8JmH/QOOQsdZBbIxZmIVUjOlWtFop9GJOEkunvKBrUV93TuYRuIMa/7CYX1ca5xGrao32z/7lpX959h@azy8Ad14gubTqvrczf3ebNPSYgP9rO0xQ4LZRGLnc/CyxuhU2Jr9nGBY/lrTy8NaxjqtTBBr/GsxVAB0v5Vspko07z1puyJhCzGzNlmn9aEr215gUVN6Gb7N/3UAfxVNBj/8A)