Sorting and Taking the Top Rows
~9 mincode completion
Write top_scores(df, n) that returns the n rows with the highest score, highest first.
Examples
The two highest scores come back, highest first
- Input
- top_scores({"name": ["a", "b", "c"], "score": [70, 95, 82]}, 2)
- Output
- [95, 82]
Asking for one row gives just the single best
- Input
- top_scores({"name": ["a", "b"], "score": [10, 20]}, 1)
- Output
- [20]
Asking for more rows than exist returns everything available
- Input
- top_scores({"name": ["a"], "score": [5]}, 10)
- Output
- [5]
Hints
Hint 1
Sorting first makes the rest straightforward.
Hint 2
Watch for this: sorted ascending.
Requirements
: a DataFrame with a "score" column
n: how many rows to returnReturn a DataFrame of n rows, ordered from highest score down.
Constraints
Standard library only, no imports required
Time limit: 200 ms, Memory: 64 MB
Where this shows up
~9 min
••••••••••••••••
8 employers weight this skill
2 big tech firms, 2 frontier labs, 1 AI product company, 1 defense company, 1 enterprise vendor, 1 quant fund. Top match scores 63.
Python
import pandas as pd
def top_scores(df, n):
"""
The n highest-scoring rows.
Args:
df: a DataFrame with a "score" column
n: how many rows to return
Returns:
A DataFrame of n rows, ordered from highest score down.
"""
# YOUR CODE HERE
pass
def _scores(df, n):
import pandas as pd
return [float(v) for v in top_scores(pd.DataFrame(df), n)["score"]]