如何正确消除字典中的元素,直到保留一个字符串

时间:2012-11-26 16:35:12

标签: python dictionary

我真的需要帮助

def get_winner (dict_winner):
    new_dict = {} 
    for winner in dict_winner:
        first_letter = winner[0]
        value = dict_winner[winner]
        if first_letter in new_dict:
            new_dict[first_letter] += value
        else:
            new_dict[first_letter] = value
    return (new_dict)


get_winner({
    ('C', 'A', 'B', 'D') :3,
    ('D', 'B', 'C', 'A') :2,
    ('C', 'D', 'A', 'B') :1,
    ('A', 'D', 'B', 'C') :2,
    ('A', 'D', 'C', 'B') :4, 
    ('A', 'C', 'D', 'B') :2
})

#Outputs {'A': 8, 'D': 2, 'C': 4}

现在我希望结果是str的元组,NoneType ..

此外,它只消除了一次只有最小值的字母。我想让它重复这个过程,直到我最终得到一个胜利者。所以在这种情况下,所有B都将在dict本身中消除,而不是在输出中消除。例如:

first time = [8, 0, 4, 2] 
second time = {
    ('C', 'A', 'D') :3, 
    ('D', 'C', 'A') :2,
    ('C', 'D', 'A') :1,
    ('A', 'D', 'C') :2,
    ('A', 'D', 'C') :4,
    ('A', 'C', 'D') :2
}) 
#Outputs C = 4 D = 2 A = 8 

third time= {
    ('C', 'A') :3, 
    ('C', 'A') :2, 
    ('C', 'A') :1, 
    ('A', 'C') :2, 
    ('A', 'C') :4,
    ('A', 'C') :2
}) 
#Outputs C = 6 A = 8

8/14> 50%,我知道从一开始就应该是这种情况,因为A已经拥有多数价值。但我假设A的值为40%,这就是消除应该开始的时候。那么,你能指出我在编码时出错了吗?在示例A应该是胜利者!所以输出的商品就是 ('A',无)

2 个答案:

答案 0 :(得分:0)

您当前的代码计算每个候选人在列表中的第一个候选人的次数。它并没有“消灭”任何人,只是因为你的一个候选人没有得到第一名的选票而给出这样做的外观。

我建议递归地做。您的基本案例是“候选人获得超过50%的选票”。像这样:

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)

答案 1 :(得分:0)

我的解决方案 - 一步到位:

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())]

这不是花哨,但很简单: - )