Sanjay Vidhya
Sanjay Vidhya

Reputation: 51

Can someone please explain how can I find the winner of each game in a dictionary?

So I'm supposed to find the winners from {P1: N1, P2: N2} where N1 and N2 are the number of games player P1 and player P2 win in the match, I have to write a function winner(records: List[Dict[str,int]]) that takes a list of all match records and returns the name of the tournament winner.

The tournament winner is determined as the player with the most wins from each input.

Also, The function should return a string - if it cannot determine the winner.

Example

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}]) == '-'

Here is my attempt at the code so far...

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 '-'

But it doesn't really work... what changes to my code should I make??

Upvotes: 1

Views: 647

Answers (1)

Jayvee
Jayvee

Reputation: 10875

Adapting your code a bit, this should give the desired results:

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)

Upvotes: 1

Related Questions