def rank(vals, x, norm=False, sort=True):
    """
    Returns the rank of x in list vals
    rank(x) = i if vals[i-1] <= x < vals[i]

    x    -- value to rank within values
    vals -- list of values to compute the rank of
    sort -- if True, vals will be sorted first
    norm -- if True, return normalized ranks (i.e. percentiles)
    """

    if sort:
        vals = sorted(vals)
    n = len(vals)

    for r, v in enumerate(vals):
        if v > x:
            break
    else:
        r = n

    if norm:
        r /= float(n + 1)

    return r