在列表中找到最高的骰子对

时间:2019-01-29 10:24:45

标签: python loops sum dice

我正在使用Python编写一个简单的Yatzy应用程序,但是我在寻找最佳骰子方面有些困惑。这是该函数的概述:

Input: list containing five dice.
Output: highest sum of two dice with the same number. If no pairs found, then -1.

使用Python编写此函数的最佳方法是什么?我怎样才能放大成两对或满满的房子?

谢谢。

1 个答案:

答案 0 :(得分:1)

这是一个使用collections模块的Python3解决方案。

from collections import Counter
from random import randint
roll = [randint(1, 6) for x in range(5)]

result = max([x for x, cnt in Counter(roll).items() if cnt==2] or [-1])

print(roll, '->', result)

顺便说一下,这里有一个边缘情况(4种= 2对),根据您需要的结果,您可能希望像cnt > 1那样进行比较。

相关问题