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
I need to find a way to do; if any of these options are correct then the correct option will be chosen and the dice variables are added together, eg Are two or more dice equal? YES, then score = sum of two equal dice
.
Really confused, can anyone offer help?
It's not necessary to ask dice2 == dice1
if you know the answer to dice1 == dice2
. And could be a good idea to set score to 0 even if none of the dice are equal
With just 3 dice it's probably easiest and fastest to just test the 3 possible pairs.
if dice1 == dice2 or dice1 == dice3:
score = dice1 * 2
elif dice2 == dice3:
score = dice2 * 2
else:
score = 0
If you have more than 3 dice you need to make more decisions of which score to give if there are more than one pair of equals. Here's a fast solution that returns the score from the highest pair:
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
The collections.Counter.most_common()
suggested in answer by @kaya is a possibility too but if the dice are (1, 1, 5, 5)
the first item of most_common()
will be the pair of ones. This is probably not expected if the dice is thrown at once. A solution to this could be to find the maximum from collections.Counter.items()
instead:
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
This is probably overkill just for three dice, but here is one way to do it that doesn't require duplicating code: the collections.Counter
class has a most_common
method which can tell you both what value occurs most commonly, and how many times it occurs.
from collections import Counter
def score(*dice):
(value, count), = Counter(dice).most_common(1)
return 2 * value if count >= 2 else 0
Examples:
>>> score(6, 3, 6)
12
>>> score(4, 2, 3)
0
>>> score(5, 5, 5)
10
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.