我遇到了一个用Python执行的问题,如下所示:
LeagueTable 类跟踪联赛中每个球员的得分。每场比赛结束后,玩家使用 record_result 函数记录他们的得分。
球员在联赛中的排名是使用以下逻辑计算的:
1.得分最高的玩家排名第一(排名1)。得分最低的玩家排名最后。
2.如果两名选手得分相同,则出场次数最少的选手排名较高。
3.如果两名选手的得分和比赛场数相同,则排名第一的选手排名更高。
实现返回给定排名的玩家的player_rank函数。
from collections import Counter
from collections import OrderedDict
class LeagueTable:
def __init__(self, players):
self.standings = OrderedDict([(player, Counter()) for player in players])
def record_result(self, player, score):
self.standings[player]['games_played'] += 1
self.standings[player]['score'] += score
def player_rank(self, rank):
return None
table = LeagueTable(['Mike', 'Chris', 'Arnold'])
table.record_result('Mike', 2)
table.record_result('Mike', 3)
table.record_result('Arnold', 5)
table.record_result('Chris', 5)
print(table.player_rank(1))
Run Code Online (Sandbox Code Playgroud)
我为其编写了一个超过 20 行的长解决方案,但随后我发现了该函数的较短代码,如下所示:
def player_rank(self, rank):
print(self.standings)
ranking = sorted(self.standings, key=lambda p: (
-self.standings[p]['score'], self.standings[p]['games_played'], self.standings[p]['pos']))
return ranking[rank - 1] …Run Code Online (Sandbox Code Playgroud)