![](/img/trans.png)
[英]Clicking on the correct option from a given list of options in Selenium (Python)
[英]Trying to select from multiple options, then add the correct option - very confused
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
。
真的很迷茫,有大神帮忙吗?
如果您知道 dice1 == dice2 的答案,则无需询问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
如果您有超过 3 个骰子,您需要做出更多决定,如果有一对以上的相等,则给出哪个分数。 这是一个从最高对返回分数的快速解决方案:
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
@kaya 在回答中建议的collections.Counter.most_common()
也是一种可能性,但如果骰子是(1, 1, 5, 5)
, most_common()
的第一项将是一对。 如果立即掷骰子,这可能是意料之外的。 对此的解决方案可能是从collections.Counter.items()
中找到最大值:
from collections import Counter
dice = [1, 3, 1, 4, 3, 5, 3, 6, 1, 2, 4, 5, 1, 1, 1]
score = 2 * max((v for v, c in Counter(dice).items() if c>=2), default = 0)
# 10
这对于三个骰子来说可能是多余的,但这里有一种不需要重复代码的方法: collections.Counter
class 有一个most_common
方法,它可以告诉你什么值最常出现,以及它出现的次数发生。
from collections import Counter
def score(*dice):
(value, count), = Counter(dice).most_common(1)
return 2 * value if count >= 2 else 0
例子:
>>> score(6, 3, 6)
12
>>> score(4, 2, 3)
0
>>> score(5, 5, 5)
10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.