产生最大分钟

时间:2015-07-20 03:09:16

标签: python dictionary

我正在尝试编写一个使用字典的函数,其中每个键都分配给值列表。该功能播放游戏,其中获取并比较每个键的最小值,即与游戏的获胜者有关的最小值的最大值。如果所有玩家都与他们的最小值相关联,则比较他们的第二个最小值,并且从中产生最大值产生获胜键。解决方案必须涉及字典/类/循环但不设置或递归。递归可用于打破循环。

例如:

determine_winner({'A':[1,1], 'B':[2,2], 'C':[1,1]})产生'B'(因为B的最低分数为2,大于其他玩家的最低分数为1

determine_winner({'A':[1,2,3,4], 'B':[2,3,4,1], 'C':[1,3,4,5]})产生'C'(所有玩家最初得分最低为1,但C的下一个最低值为3,而A和B的下一个最低值为2)

determine_winner({'A':[1,2,3,4], 'B':[2,3,4,1], 'C':[1,4,1,5]})产生'Tied'(所有玩家最初的得分最低为1,但A和B则为2,而C又有1,因此不再考虑。然后A和B再搭配3,最后用4,所以领带不能打破)

到目前为止我写的是产生错误:

def determine_winner(results):
    a = []
    max_mins = 0
    for key in results:
        if min(results[key]) > max_mins:
            winner = key
            max_mins = min(results[key])
        if min(results[key]) == max_mins:
            results = results[key].remove(min(results[key]))
    return winner

1 个答案:

答案 0 :(得分:2)

看起来你在循环时修改results

results = results[key].remove(min(results[key]))

删除最后一个if语句将修复错误。

对于实际程序,此版本首先对结果进行排序,然后为每个得分者循环遍历:

def determine_winner(results):
    print results
    for key in results:
        results[key].sort()          # sort all the results
        length = len(results[key])

    for l in range(length):          # examine the scores in order
        max_score = 0
        next_results = {}
        for key in results:          # compare each scorer
            score = results[key][l]
            if score < max_score:    # ignore this scorer
                continue
            if score == max_score:   # multiple high scores
                winner = 'Tied'
            else:                    # new high score
                winner = key
                max_score = score
            # prepare the results for the next round
            next_results[key] = results[key]
        results = next_results       # get ready for the next round
    print winner

determine_winner({'A':[1,1], 'B':[2,2], 'C':[1,1]})
determine_winner({'A':[1,2,3,4], 'B':[2,3,4,1], 'C':[1,3,4,5]})
determine_winner({'A':[1,2,3,4], 'B':[2,3,4,1], 'C':[1,4,1,5]})

输出如下:

{'A': [1, 1], 'C': [1, 1], 'B': [2, 2]}
B
{'A': [1, 2, 3, 4], 'C': [1, 3, 4, 5], 'B': [2, 3, 4, 1]}
C
{'A': [1, 2, 3, 4], 'C': [1, 4, 1, 5], 'B': [2, 3, 4, 1]}
Tied