gpt4 book ai didi

python - TestDome 联赛表 - Python

转载 作者:行者123 更新时间:2023-12-02 15:01:46 25 4
gpt4 key购买 nike

我遇到了一个用 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:我只是一个新手,刚开始学习编程。

原始问题的链接。

https://www.testdome.com/d/python-interview-questions/9

最佳答案

对于解决方案:

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]

整个函数基本上是根据key对player进行排序,First

-self.standing[p]['score']

根据“分数”从高到低获取降序列表,然后

self.standings[p]['games_played']

根据'games_played'再次对之前的列表进行升序排序

self.standings[p]['pos']

这应该是根据有序集合的顺序对列表进行排序,我想你错过了代码中带有“pos”的其他部分

现在你有一个列表,其中列出了所有排名,你返回具有特定排名的特定玩家

关于python - TestDome 联赛表 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48913328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com