#!/usr/bin/env python3 from fractions import Fraction from itertools import product def comps(n,r): if r==1: yield (n,) else: for a in range(1,n-r+2): for z in comps(n-a,r-1): yield (a,)+z def calc(I,J,even=False): tot=Fraction(0) for r in range(1,min(I,J)+1): for A in comps(I,r): for B in comps(J,r): K=sum(B[l]*sum(A[:l+1]) for l in range(r))% 2 for sa in product((-1,1),repeat=r): x=sum(sa[l]*A[l] for l in range(r)) for sb in product((-1,1),repeat=r): y=sum(sb[l]*B[l] for l in range(r)) if (x+2*y)% 5: continue if even: ok=True else: delta=(1 if I% 4==2 else 0)+(1 if J% 4==2 else 0) ok=((x+y)//2+K+delta)% 2==1 if ok: e=(abs(2*x-y)+abs(x+2*y)+abs(-3*x-y))//2 tot+=Fraction(e,2*r) return tot print(calc(2,10),calc(10,2),calc(4,8),calc(8,4),calc(6,6)) print(calc(6,6,True)) print(sum((calc(I,12-I,True) for I in [2,4,6,8,10]),Fraction(0)))