尝试从多个选项中进行选择,然后添加正确的选项-非常困惑
if (dice1 == dice2) or (dice1 == dice3) or (dice2 == dice1) or (dice2 == dice3)
or (dice3 == dice2) or (dice3 == dice1):
score = # no clue what to put here
我需要找到办法;如果这些选项中的任何一个是正确的,那么将选择正确的选项并将骰子变量加在一起,例如两个或多个骰子是否相等?是的,那么score = sum of two equal dice。
真的很困惑,谁能提供帮助?
回答
没有必要问dice2 == dice1你是否知道答案dice1 == dice2。即使没有一个骰子相等,将分数设置为 0 也是一个好主意
仅使用 3 个骰子,测试 3 个可能的对可能是最简单和最快的。
if dice1 == dice2 or dice1 == dice3:
score = dice1 * 2
elif dice2 == dice3:
score = dice2 * 2
else:
score = 0
if dice1 == dice2 or dice1 == dice3:
score = dice1 * 2
elif dice2 == dice3:
score = dice2 * 2
else:
score = 0
如果您有 3 个以上的骰子,您需要做出更多决定,如果有多个相等的对子,则要给出哪个分数。这是一个快速解决方案,它返回最高对的分数:
在collections.Counter.most_common()通过@kaya在回答提出的一种可能性太多,但如果骰子(1, 1, 5, 5)的第一个项目most_common()将是对那些的。如果一次掷骰子,这可能不是预期的。对此的解决方案可能是从以下位置找到最大值collections.Counter.items():
def best_pair(dice):
candidates = set()
best = 0
for die in dice:
# don't bother if it's not better than best
if die > best:
# did we find an equal before?
if die in candidates:
# then it's the new best
best = die
else:
# maybe next time...
candidates.add(die)
return best * 2
best_pair([1, 3, 1, 4, 3, 5, 3, 6, 1, 2, 4, 5, 1, 1, 1])
# 10