File tree Expand file tree Collapse file tree 2 files changed +60
-0
lines changed Expand file tree Collapse file tree 2 files changed +60
-0
lines changed Original file line number Diff line number Diff line change 1+ <p >Table: <code >Scores</code ></p >
2+
3+ <pre >
4+ +-------------+---------+
5+ | Column Name | Type |
6+ +-------------+---------+
7+ | id | int |
8+ | score | decimal |
9+ +-------------+---------+
10+ id is the primary key (column with unique values) for this table.
11+ Each row of this table contains the score of a game. Score is a floating point value with two decimal places.
12+ </pre >
13+
14+ <p >  ; </p >
15+
16+ <p >Write a solution to find the rank of the scores. The ranking should be calculated according to the following rules:</p >
17+
18+ <ul >
19+ <li>The scores should be ranked from the highest to the lowest.</li>
20+ <li>If there is a tie between two scores, both should have the same ranking.</li>
21+ <li>After a tie, the next ranking number should be the next consecutive integer value. In other words, there should be no holes between ranks.</li>
22+ </ul >
23+
24+ <p >Return the result table ordered by <code >score</code > in descending order.</p >
25+
26+ <p >The result format is in the following example.</p >
27+
28+ <p >  ; </p >
29+ <p ><strong class =" example " >Example 1:</strong ></p >
30+
31+ <pre >
32+ <strong >Input:</strong >
33+ Scores table:
34+ +----+-------+
35+ | id | score |
36+ +----+-------+
37+ | 1 | 3.50 |
38+ | 2 | 3.65 |
39+ | 3 | 4.00 |
40+ | 4 | 3.85 |
41+ | 5 | 4.00 |
42+ | 6 | 3.65 |
43+ +----+-------+
44+ <strong >Output:</strong >
45+ +-------+------+
46+ | score | rank |
47+ +-------+------+
48+ | 4.00 | 1 |
49+ | 4.00 | 1 |
50+ | 3.85 | 2 |
51+ | 3.65 | 3 |
52+ | 3.65 | 3 |
53+ | 3.50 | 4 |
54+ +-------+------+
55+ </pre >
Original file line number Diff line number Diff line change 1+ import pandas as pd
2+
3+ def order_scores (scores : pd .DataFrame ) -> pd .DataFrame :
4+ scores ['rank' ] = scores ['score' ].rank (method = 'dense' , ascending = False )
5+ return scores [['score' , 'rank' ]].sort_values ('score' , ascending = False )
You can’t perform that action at this time.
0 commit comments