# independent check, N=8, k=3: weight w(pi) by cycle type of M u pi(M): 8-cycle -> 0, two 4-cycles -> 5, else 1.
# verify every ordered triple a -> b has total weight exactly 8!/(8*7*6) = 120.
import itertools
N=8; partner=[i^1 for i in range(N)]
def ctype(p):
    blue={}
    for i in range(0,N,2): blue[p[i]]=p[i+1]; blue[p[i+1]]=p[i]
    seen=set(); t=[]
    for v in range(N):
        if v in seen: continue
        L=0; x=v
        while x not in seen:
            seen.add(x); y=partner[x]; seen.add(y); L+=2; x=blue[y]
        t.append(L)
    return tuple(sorted(t))
from collections import defaultdict
W=defaultdict(int); tot=0
reps=[(0,1,2),(0,2,4),(0,2,3),(0,1,4)]  # red-pattern representatives incl. orderings
cnt={r:defaultdict(int) for r in reps}
for p in itertools.permutations(range(N)):
    t=ctype(p); w=0 if t==(8,) else 5 if t==(4,4) else 1
    tot+=w
    if w:
        for r in reps: cnt[r][(p[r[0]],p[r[1]],p[r[2]])]+=w
print("total weight",tot,"(8! =",40320,")")
for r in reps:
    vals=set(cnt[r].values()); print(r,"images:",len(cnt[r]),"weights:",vals)
