rookie
rookie

Reputation: 31

I want to roll 3 dice with independent numbers from each other

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

Upvotes: 3

Views: 3283

Answers (5)

FxIII
FxIII

Reputation: 418

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

Upvotes: 0

johnsyweb
johnsyweb

Reputation: 141860

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.

Upvotes: 2

Mark Byers
Mark Byers

Reputation: 838696

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.

Upvotes: 8

escargot agile
escargot agile

Reputation: 22389

This will work:

a = range(1,7)
random.shuffle(a)
a[:3]

Upvotes: 3

sahhhm
sahhhm

Reputation: 5365

A simplistic approach would be

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

Random Documentation

Upvotes: 2

Related Questions