3

I want to write a python program that will simulate 3 dice being rolled at the same time but I want the 3 dice to always have a different number from each other every time they are rolled. ex on the first roll I get 2,1,6 that is fine but I dont want the prog. to ever roll duplicates for ex 2,4,2. (3,3,3, would also be unacceptable)

# generating random numbers 1 - 6
die1 = random.randint(1, 6) 

die2 = random.randrange(1, 6)

die3 = random.randrange(1, 6)

this is all I have so far, im a beginner ... Thanks

johnsyweb
  • 136,902
  • 23
  • 188
  • 247
rookie
  • 31
  • 1
  • 2
  • Have a look at this question if you are interested in the algorithm itself as well, rather than only in the solution http://stackoverflow.com/questions/311703/algorithm-for-sampling-without-replacement – Dr G Dec 28 '10 at 00:12
  • 2
    Note: *independent* in this context is usually understood to mean that the outcome of one die doesn't affect the outcome of the others. That's almost the exact opposite of what you want. I think the word you are looking for is *distinct*. – Mark Byers Dec 28 '10 at 00:13

5 Answers5

8

Try random.sample:

>>> sides = 6
>>> dice = random.sample(range(1, sides + 1), 3)
[3, 6, 1]

I'd advise that you reconsider whether it is a good idea to have variables called die1, die2, die3.

It is usually better to use a list as in the above example.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
3

This will work:

a = range(1,7)
random.shuffle(a)
a[:3]
Ilya Kogan
  • 21,995
  • 15
  • 85
  • 141
  • Nice approach. Much better than rolling three independent dice and then re-rolling the duplicates. – kindall Dec 28 '10 at 00:51
2

A simplistic approach would be

import random
die1, die2, die3 = random.sample([1,2,3,4,5,6], 3)

Random Documentation

sahhhm
  • 5,325
  • 2
  • 27
  • 22
2

This isn't the usual behaviour of three dice, but you could do:

import random
[die1, die2, die3] = random.sample(xrange(1, 7), 3)

Here's the documentation on random.sample() and xrange() for your reference.

johnsyweb
  • 136,902
  • 23
  • 188
  • 247
0

If you are going to roll multiple times, is better to store the range(1,7) somewhere and use the sample function instead of the shuffle one (obvously because 'shuffle' shuffles all the range)

take a look on this:

import random,time
N=80000
a = range(1,7)
t= time.clock()
for i in xrange(N):
    random.shuffle(a)
    a[:3]
t= time.clock()-t
print t

t= time.clock()
for i in xrange(N):
    dice = random.sample(range(1, 6 + 1), 3)
t= time.clock()-t
print t

t= time.clock()
for i in xrange(N):
    dice = random.sample(a, 3)
t= time.clock()-t
print t
FxIII
  • 408
  • 5
  • 12