if ref == seq:
    return 0
else:
    rank = 0
f = math.factorial(len(seq) - 1)
for x in ref:
    if x < seq[0]:
        rank += f
else:
    rank += permutation_rank(seq[1:]) if seq[1:] else 0
return rank
Rank of a Permutation