How to properly eliminate elements in dictionary until one string remains

前端 未结 2 1207
梦谈多话
梦谈多话 2021-01-26 09:28

I really need help on this

def get_winner (dict_winner):
    new_dict = {} 
    for winner in dict_winner:
        first_letter = winner[0]
        value = dict_         


        
相关标签:
2条回答
  • 2021-01-26 09:45

    Your current code counts the number of times each candidate is the first on the list. It doesn't "eliminate" anyone, it just gives the appearance of doing so since one of your candidates gets no first-place votes.

    I suggest doing it recursively. Your base case is "a candidate gets over 50% of the vote". Something like this:

    def get_winner(vote_dict)
        total_votes = sum(vote_dict.values())
        votes_by_candidate = defaultdict(int)    # This makes your if/else block redundant
    
        for vote_pattern in vote_dict:
            votes_by_candidate[vote_pattern[0]] += vote_dict[vote_pattern]
    
        for candidate in votes_by_candidate:
             if votes_by_candidate[candidate] * 2 > total_votes:
                 return candidate
    
        new_dict = defaultdict(int)
        eliminated = min(votes_by_candidate, key=votes_by_candidate.get)
    
        for vote_pattern in vote_dict:
            new_pattern = [candidate for candidate in vote_pattern if candidate != eliminated]
            new_dict[new_pattern] += vote_dict[vote_pattern]
    
        return get_winner(new_dict)
    
    0 讨论(0)
  • 2021-01-26 10:04

    My solution - in one step:

    def get_winner(candidates):
        winners = dict.fromkeys(map(lambda f: f[0] for f in candidates.keys()))
        for cand, votes in candidates.iteritems(): 
            winners[cand[0]]+=votes
        return [winner for winner, vote in winners.iteritems() if vote ==max(winners.values())]
    

    It is not fancy, but it is simple :-)

    0 讨论(0)
提交回复
热议问题