import math


def rank_permutation(seq):
    ref = sorted(seq)
    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 += rank_permutation(seq[1:]) if seq[1:] else 0
                return rank


def unrank_permutation(n, k):
    """
    Generates the k-th permutation of size n.

    Args:
        n: The size of the permutation.
        k: The rank of the permutation (0-indexed).

    Returns:
        A list representing the k-th permutation of size n.
    """
    if not (0 <= k < math.factorial(n)):
        raise ValueError("Rank k is out of bounds.")

    items = list(range(n))
    permutation = []
    temp_k = k

    for i in range(n, 0, -1):
        index = temp_k // math.factorial(i - 1)
        temp_k %= math.factorial(i - 1)
        permutation.append(items.pop(index))
    
    return permutation


def binomial(n,k):
    if n < 0 or k < 0 or k > n: return 0
    b = 1
    for i in range(k): b = b*(n-i)//(i+1)
    return b


def unchoose(n,S):
    k = len(S)
    if k == 0 or k == n: return 0
    j = S[0]
    if k == 1: return j
    S = [x-1 for x in S]
    if not j: return unchoose(n-1,S[1:])
    return binomial(n-1,k-1)+unchoose(n-1,S)


def choose(X,k):
    n = len(X)
    if k < 0 or k > n: return []
    if not k: return [[]]
    if k == n: return [X]
    return [X[:1] + S for S in choose(X[1:],k-1)] + choose(X[1:],k)


def unget(perm, n):
  zipped = zip(perm, range(len(perm)))
  return list(zipped)

print(unget([0, 2, 1], 4))
