def mode(var, k=1):
    """
    Returns the `k`th most probable value of the random variable `var`.
    """

    pairs = sorted(var._dist.keys(), key=lambda val: var[val], reverse=True)
    return pairs[k - 1]