"""Exact fixed-point factorial moments and the alternating-binomial tail used for the correction.""" from fractions import Fraction as F from math import comb, factorial derangements=[1,0] for n in range(2,51): derangements.append((n-1)*(derangements[n-1]+derangements[n-2])) cases=0 for n in range(3,51): mass=[F(comb(n,z)*derangements[n-z],factorial(n)) for z in range(n+1)] assert sum(mass)==1 for m in range(n//2+1): trunc=[sum((-1)**j*comb(z,j) for j in range(min(z,m)+1)) for z in range(n+1)] assert trunc[0]==1 and all(x==0 for x in trunc[1:m+1]) assert all(trunc[z]==(-1)**m*comb(z-1,m) for z in range(m+1,n+1)) exact=sum(p*comb(z,m+1) for z,p in enumerate(mass) if z>m) tail=sum(p*comb(z-1,m) for z,p in enumerate(mass) if z>m) assert 0<=tail<=exact==F(1,factorial(m+1)) cases+=1 print('Uniform permutations for 3 through 50 labels.') print(cases,'alternating fixed-point and factorial-moment identities verified exactly.')