views:

54

answers:

1

(sorry if this is a dumb question, I'm still learning)

I'm making a program that, for part of the prog, 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

Thats 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 leftover? Or is the code I'm using the best way to do it?

+7  A: 

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
Mark Byers
so dice = [random.randint(1, 6) for x in range(4)]sum(dice) - min(dice)replaces that entire block I posted? lol I wasted a lot of time it looks like. is x a variable or is that just part of the function?
Matt
@Matt: Yes, that is all you need. The `x` is an unused variable.
Mark Byers
Fun tip: You may use `_` as a placeholder for an unused variable. For example: `[random.randint(1, 6) for _ in range(4)]`
jathanism
Since the `_` variable has a special meaning in interactive sessions (it contains the last result), I recommend not using as suggested here.
taleinat
If min is simpler *and* faster than your first solution, then it should be preferred?
Paul Hankin
@Paul Hankin: Yes. The only reason why I wrote the first solution is because that was how the problem was described and that's the approach I first used. As far as I can see the first approach is only useful if you have to remove the x lowest dice for x > 1.
Mark Byers