from fractions import Fraction as F from copy import deepcopy as cp from itertools import product from json import dumps,loads M=loads('{"v":"treeOS.universal/1.1","by":"Matthew Alan Newman (@NVE024)","shape":"[P,[u,a,L,R],H];top=end;blank=0","rule":"[u,a,v,b,d];d=-1,0,1;bits;unique(u,a);P immutable","q":"339949771344778/1000000000000000","mode":"0=bits;1=[depth,hex numerator,hex denominator]","api":"hop(seed,n,src,dst)->(seed,actual_steps);n<0=undo","scope":"exact codecs/transport/history consistency;universality=model argument","budget":23}') q=F(M["q"]) I=lambda x:type(x)is int B=lambda x:I(x) and x in (0,1) def ok(x): if not x:raise ValueError('invalid seed') def e(s): ok(type(s)is list and all(map(B,s)));x=F(1,2) for b in s:x=q*x+(1-q)*b return[len(s),hex(x.numerator),hex(x.denominator)] def d(c): ok(type(c)is list and len(c)==3) n,a,b=c;ok(I(n) and n>=0 and type(a)is str and type(b)is str) A=int(a,16);D=int(b,16);ok(0F(1,2));x-=(1-q)*b;ok(00 else(r,l);ok(bool(dst));x=dst.pop();ok(x==t) if z:ok(a==0 and not src) else:src.append(a) else:ok(not z and a==t) u,a=v,b else: i=next((i for i,t in enumerate(p) if t[:2]==[u,a]),None) if i is None:break _,_,v,b,g=p[i];z=False if g: dst,src=(l,r) if g>0 else(r,l);dst.append(b);z=not src;a=src.pop() if src else 0 else:a=b u=v;h.append([i,z]) k+=1 c[:2]=[u,a];return k def hop(s,n,a=0,b=0): ok(I(n) and B(a) and B(b));t=loads(dumps(s));t=D(t) if a else t;valid(t) ok(n>=-len(t[2]));_run(cp(t),-len(t[2]));k=_run(t,n) return(E(t) if b else t),k if __name__=='__main__': s=[[[0,0,1,1,1],[1,0,2,1,-1]],[0,0,[],[]],[]] for n in range(9): for w in product((0,1),repeat=n):ok(d(e(list(w)))==list(w)) x=[0,1]*200;ok(d(e(x))==x) ok(D(E(s))==s) t,k=hop(s,M["budget"],0,1);t=loads(dumps(t));ok(k==2 and D(t)[1][:2]==[2,1]);ok(hop(t,-k,1,0)[0]==s) u,j=hop(s,1,0,1);v,k=hop(u,1,1,0);ok(v==hop(s,2)[0]) for a,b,g,l,r in product((0,1),(0,1),(-1,0,1),[[],[0],[1],[0,1]],[[],[0],[1],[0,1]]): s=[[[0,a,1,b,g]],[0,a,l,r],[]];T={0:b} T.update({-i:x for i,x in enumerate(l[::-1],1)});T.update({i:x for i,x in enumerate(r[::-1],1)}) C=[1,T.get(g,0),[T.get(i,0) for i in range(min(-len(l),g),g)],[T.get(i,0) for i in range(max(len(r),g),g,-1)]] for src,dst in product((0,1),repeat=2): w=E(s) if src else cp(s);t,k=hop(w,1,src,dst);ok((D(t) if dst else t)[1]==C);ok(hop(t,-k,dst,src)[0]==w) def bad(f,x): old=cp(x) try:f(x) except (ValueError,TypeError,IndexError,ZeroDivisionError):ok(x==old);return raise ValueError('accepted invalid input') for c in [[1,'0x1','0x2'],[0,'0x2','0x4'],[-1,'0x1','0x2'],[0,'0X1','0x2'],[0,'0x1','0x0']]:bad(d,c) t,k=hop([[[0,0,1,1,1]],[0,0,[],[]],[]],1) for i,z in [(-1,False),(0,0)]: t[2][0]=[i,z];bad(lambda x:hop(x,-1),t) t[2]=[[0,True]];t[1][0]=2;bad(lambda x:hop(x,-1),t) print('PASS: codec, transport, inverse, rejection')