You are given a list of player names players and a sequence of matches played between them. Implement the Elo rating system to compute each player's final rating after all matches are processed in order.
Each player starts with an initial rating of 1500. For a match between player A (rating RA) and player B (rating RB), the expected scores are
EA=1+10(RB−RA)/4001,EB=1−EA
Given A's actual score SA and SB=1−SA, both ratings are updated with K=32:
RA′=RA+K(SA−EA),RB′=RB+K(SB−EB)
Each match is given as [player_a, player_b, result], where result is "1" if A wins, "0" if B wins, and "2" if the match is a draw (both players score 0.5).
Return the final ratings rounded to the nearest integer (half away from zero), in the same order as the players list.
Function Signature
def final_ratings(players: list[str], matches: list[list[str]]) -> list[int]:
Rules
-
Both expected scores and both updates for a match use the two ratings from just before that match.
-
Ratings are kept as unrounded floating-point values between matches. Only the final ratings are rounded.
-
Half away from zero means 2.5 becomes 3 and -2.5 becomes -3.
-
The result code arrives as a string, as in the examples.
Constraints
-
2 <= len(players) <= 10^4
-
All names in
players
are unique and consist of lowercase English letters.
-
1 <= len(players[i]) <= 20
-
0 <= len(matches) <= 10^4
-
Each match references two distinct players present in
players
.
-
matches[i][2]
is
"0"
,
"1"
or
"2"
.
Examples
Input: players = ["alice","bob"], matches = [["alice","bob","1"]]
Output: [1516,1484]
Both start at 1500, so each expected score is 0.5. Alice wins and gains 32 * (1 - 0.5) = 16, and Bob loses the same 16.
Input: players = ["a","b","c"], matches = [["a","b","1"],["b","c","2"],["a","c","0"]]
Output: [1499,1485,1516]
After the first match a is at 1516 and b at 1484. In the draw, b is the lower-rated player (expected score about 0.477), so b gains about 0.74 and c drops to about 1499.26. In the last match c beats a, whose expected score was about 0.524, so a loses about 16.77 and c gains the same amount. The unrounded finals are about 1499.23, 1484.74 and 1516.03.
Input: players = ["x","y"], matches = []
Output: [1500,1500]
With no matches, every player keeps the starting rating.