def up_to(last): return range(last+1) def has_no_repeats(square): for i in up_to(15): for j in up_to(i-1): if square[i]==square[j]: return 0 # i.e., there *is* a repeat. return 1 # we finished without finding a repeat. Hooray! a,b,c,d = 10,2,20,00 for m in up_to(b+c): p = b+c-m for g in up_to(a+p): j = a+p-g for f in up_to(d+m): k = d+m-f n = g+k-b if n<0: continue o = f+j-c if o<0: continue for h in up_to(a+m): l = a+m-h e = j+k-h i = f+g-l if e<0 or i<0: continue if has_no_repeats([a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p]): print a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p