Is there a more efficient way to organize random outcomes by size in Python?
I'm making a program that, in part, rolls four dice and subtracts the lowest dice from the outcome. The code I'm using is
die1 = random.randrange(6) + 1
die2 = random.randrange(6) + 1
die3 = random.randrange(6) + 1
die4 = random.randrange(6) + 1
if die1 <= die2 and die1 <= die3 and die1 <= die4:
drop = die1
elif die2 <= die1 and die2 <= die3 and die2 <= die4:
drop = die2
elif die3 <= die1 and die3 <= die2 and die3 <= die4:
drop = die3
else:
drop = die4
cha = die1 + die2 + die3 + die4 - drop
That's the best I could come up with from my so-far limited coding ability. Is there a better way to make it organize the four dice in order of size, then add together the three highest while ignoring the lef开发者_开发知识库tover? Or is the code I'm using the best way to do it?
Put the dice in a list, sort the list using sorted
and remove the smallest element using a slice:
>>> import random
>>> dice = [random.randint(1, 6) for x in range(4)]
>>> sum(sorted(dice)[1:])
13
Or an alternative that is simpler and will also be faster if you have lots of dice: use min to find the minimum die and subtract it from the sum of them all:
>>> sum(dice) - min(dice)
13
精彩评论