pandas: The top n rows

Model df.nlargest(n, "value"), which keeps the first rows on ties.

What to build

A program that prints the rows with the largest values.

Requirements

  • Print the n rows with the largest values, from largest to smallest, as NAME VALUE; among equal values, earlier rows come first. If there are fewer than n rows, print them all.

Input

Line 1: n. Line 2: m, the number of rows. Then m lines NAME,VALUE.

Output

min(n, m) lines.

Constraints

1 ≤ n ≤ 100; 1 ≤ m ≤ 1000; values are whole numbers.

Example

Input:

2
3
a,5
b,9
c,7

Output:

b 9
c 7

Why it works

A stable sort by the negated value orders rows from largest to smallest while keeping tied rows in their original order, which is what keep="first" means.

Examples

Example 1 · Input
2
3
a,5
b,9
c,7
Expected output
b 9
c 7
Example 2 · Input
1
1
x,1
Expected output
x 1

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

Hints

Hint 1

Sort by the value from largest to smallest with a stable sort, then take the first n.

Hint 2

If there are fewer rows than n, all rows are returned.

Solution

Show one correct solution (try it yourself first)
n = int(input())
m = int(input())
rows = [input().split(",") for _ in range(m)]
rows.sort(key=lambda r: -int(r[1]))
for name, value in rows[:n]:
    print(name, value)

Lesson: A complete analysis with pandas →