from collections import Counter, defaultdict
from itertools import combinations, permutations
from math import factorial, prod


def check_coefficients():
    coefficients = [1]
    for n in range(1, 51):
        previous = coefficients
        coefficients = [0] * (len(previous) + n - 1)
        for shift in range(n):
            for j, value in enumerate(previous):
                coefficients[j + shift] += value
        assert sum(coefficients) == factorial(n)
        assert coefficients == coefficients[::-1]
        for m in range(1, len(coefficients) - 1):
            assert coefficients[m] ** 2 >= coefficients[m - 1] * coefficients[m + 1]
        for m in range(1, len(coefficients)):
            assert m * coefficients[m] <= (m + n - 1) * coefficients[m - 1]


def relative_order(block):
    rank = {value: index for index, value in enumerate(sorted(block))}
    return tuple(rank[value] for value in block)


def inversions(values):
    return sum(first > second for first, second in combinations(values, 2))


def check_blocks():
    for k in (2, 3, 4):
        histograms = defaultdict(Counter)
        blocks = [range(start, min(start + k, 8)) for start in range(0, 8, k)]
        for permutation in permutations(range(8)):
            orders = tuple(relative_order(permutation[b.start:b.stop]) for b in blocks)
            cross = inversions(permutation) - sum(map(inversions, orders))
            histograms[orders][cross] += 1
        assert len(histograms) == prod(factorial(len(b)) for b in blocks)
        reference = next(iter(histograms.values()))
        assert all(histogram == reference for histogram in histograms.values())


if __name__ == "__main__":
    check_coefficients()
    check_blocks()
    print("Verified coefficient inequalities through n=50.")
    print("Verified block factorization on S_8 for k=2,3,4.")
