当前位置: 首页 > 知识库问答 >
问题:

有人能解释一下我如何在字典里找到每场比赛的获胜者吗?

段晨
2023-03-14

所以我应该从{P1:N1,P2:N2}中找到赢家,其中N1和N2是玩家P1和玩家P2在比赛中获胜的游戏数,我必须编写一个函数winner(records:List[Dict[str,int]]),它获取所有比赛记录的列表并返回锦标赛赢家的名字。

锦标赛获胜者被确定为每个输入中获胜次数最多的玩家。

此外,如果不能确定获胜者,函数应该返回字符串-

示例

assert winner([{'A':2,'B':1}]) == 'A'
assert winner([{'A':3,'B':0},{'A':1,'C':2}]) == '-'
assert winner([{'A':3,'B':0},{'A':1,'C':2},{'B':0,'C':3}]) == 'C'
assert winner([{'A':3,'B':0},{'A':1,'C':2},{'B':0,'D':3},{'A':2,'D':1}]) == 'A'
assert winner([{'A':3,'B':0},{'B':2,'C':1},{'C':2,'D':1},{'A':0,'D':3}]) == '-'

这是我到目前为止对代码的尝试...

def finder(records):
    for x in winners:
        return max(x, key = x.get)
def winner(records):
    for x in finder(records):
        if x.count == max(x.count):
           return x
        else:
           return '-'

但是它真的不起作用...我应该对我的代码做什么修改??

共有1个答案

钮长恨
2023-03-14

稍微调整一下您的代码,这将得到预期的结果:

def winner(records):
    winners={} # dictionary to keep players and number of wins
    
    for x in records:       
        maxplayer= max(x,key=x.get) # find winner player
        # update dict of winners
        if maxplayer in winners:
            winners[maxplayer]+=1
        else:
            winners.update({maxplayer:1})
    
    maxpoints=max(winners.values()) # find total points winner(s)
    
    # if more than 1 player with max points is a tie 
    if list(winners.values()).count(maxpoints)>1:
        return "-"
    else:
        return max(winners, key=winners.get)
 类似资料: