![](/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.