Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate three different random numbers [duplicate]

Tags:

python

I've got something here, but I can't get it working how I like it:

def nested_loops():
    import random
    option1 = random.randint(1, 3)
    option2 = random.randint(1, 3)
    option3 = random.randint(1, 3)

The bit above generates numbers, but they may be the same. The below code this should fix that, but it doesn't, but it just seems to decrease the likelihood:

while option1 == option2:
    option1 = random.randint(1,3)
    while option1 == option3:
        option1 = random.randint(1, 3)
        while option2 == option3:
            option2 = random.randint(1, 3)

print(option1)
print(option2)
print(option3)

It is fairly obvious it just prints them.

like image 559
user3258159 Avatar asked Mar 22 '14 12:03

user3258159


2 Answers

You can use random.sample to get any amount of unique 'random' items from an iterable- there is no need to use nested loops:

>>> option1, option2, option3 = random.sample(range(1, 4), 3)
>>> option1, option2, option3
(3, 1, 2)
like image 93
anon582847382 Avatar answered Oct 12 '22 17:10

anon582847382


The bug in your code is that if option1 and option2 are different, the first while won't be entered, and you won't examine if any of them are equal to option3.

like image 23
elias Avatar answered Oct 12 '22 19:10

elias