pandas: Rank with every tie method

Model Series.rank and its five ways of handling ties.

What to build

A program that ranks values with a chosen method and direction.

Requirements

  • For each query METHOD DIRECTION (METHOD is average, min, max, dense or first; DIRECTION asc or desc), print the ranks of the values in input order, separated by spaces, each with one decimal place. A missing value (NaN) has the rank NaN.

Input

Line 1: the values separated by spaces (numbers or NaN). Line 2: q. Then q queries.

Output

q lines.

Constraints

1 to 100 values; 1 ≤ q ≤ 10.

Example

Input:

88 92 88 NaN 75
3
average desc
min desc
dense asc

Output:

2.5 1.0 2.5 NaN 4.0
2.0 1.0 2.0 NaN 4.0
2.0 3.0 2.0 NaN 1.0

Why it works

Every method agrees on the order and differs only in what tied values receive, which is why each method gives the same ranks to a list with no ties.

Examples

Example 1 · Input
88 92 88 NaN 75
3
average desc
min desc
dense asc
Expected output
2.5 1.0 2.5 NaN 4.0
2.0 1.0 2.0 NaN 4.0
2.0 3.0 2.0 NaN 1.0
Example 2 · Input
10 20 10 10
2
max asc
first asc
Expected output
3.0 4.0 3.0 3.0
1.0 4.0 2.0 3.0

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Sort the present values (descending if asked) and find, for each value, the first and last place it occupies.

Hint 2

average is the mean of those places, min the first, max the last; dense counts distinct values; first uses the order of appearance.

Solution

Show one correct solution (try it yourself first)
values = [None if v == "NaN" else float(v) for v in input().split()]
q = int(input())
for _ in range(q):
    method, direction = input().split()
    present = sorted([v for v in values if v is not None], reverse=direction == "desc")
    distinct = sorted(set(present), reverse=direction == "desc")
    seen = {}
    ranks = []
    for v in values:
        if v is None:
            ranks.append("NaN")
            continue
        first = present.index(v) + 1
        last = len(present) - present[::-1].index(v)
        if method == "average":
            r = (first + last) / 2
        elif method == "min":
            r = first
        elif method == "max":
            r = last
        elif method == "dense":
            r = distinct.index(v) + 1
        else:
            r = first + seen.get(v, 0)
            seen[v] = seen.get(v, 0) + 1
        ranks.append(f"{r:.1f}")
    print(" ".join(ranks))

Lesson: Sorting, ranking and counting →