from collections import Counter
from fractions import Fraction
from itertools import combinations, permutations


pattern = (2, 3, 4, 5, 1)
counts = Counter()
occurrences = Counter()
for permutation in permutations(range(1, 8)):
    m = sum(a > b for a, b in combinations(permutation, 2))
    if m in (7, 8, 9):
        counts[m] += 1
        for start in range(3):
            window = permutation[start:start + 5]
            ranks = {x: i for i, x in enumerate(sorted(window), 1)}
            if tuple(ranks[x] for x in window) == pattern:
                occurrences[m] += 1

print("m   permutations   occurrences   mean")
means = []
for m in (7, 8, 9):
    mean = Fraction(occurrences[m], counts[m])
    print(f"{m}  {counts[m]:12}  {occurrences[m]:12}   {mean}")
    means.append(mean)
assert means[0] > means[1] < means[2]
