我遇到了一个如下问题,在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))
我为它编写了一个超过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]
有人可以帮我理解这是如何运作的吗?
P.S:我只是个新手,开始学习编程。链接到原始问题。
答案 0 :(得分:1)
对于解决方案:
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]
整个功能基本上是根据键来排序玩家,第一个
-self.standing[p]['score']
根据'得分'获取降序列表这意味着从最高到最低,然后
self.standings[p]['games_played']
根据' games_played'
将上一个列表再次按升序排序self.standings[p]['pos']
这个应该根据有序集合的顺序对列表进行排序,我想你错过了其他部分的代码' pos'
现在你有一个列出所有等级的列表,你返回具有特定等级的特定玩家
答案 1 :(得分:0)
从2019年开始解决该问题,通过了4个测试用例。
def player_rank(self, rank):
srt = sorted(
self.standings.items(),
key=lambda kv: (
-kv[1]['score'],
kv[1]['games_played'],
),
reverse=False)
# print(srt)
return srt[rank - 1][0]