简体   繁体   中英

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

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.

This will work:

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

A simplistic approach would be

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

Random Documentation

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.

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM