20

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user3258159
  • 217
  • 1
  • 2
  • 7
  • 1
    Agree that based on the accepted answer this is a duplicate, but feel the need to point out that import random;alist = [x+1 for x in range(3)]; random.shuffle(alist) will handle the case where the list is 1 to N (in this case 3) – Foon Dec 06 '15 at 13:06

2 Answers2

36

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)
anon582847382
  • 19,907
  • 5
  • 54
  • 57
1

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.

elias
  • 849
  • 13
  • 28
  • If you are looking for a rejection-free implementation, I suggest to check out my answer from yesterday in this other thread: http://stackoverflow.com/questions/22563558/bug-in-random-numbers-in-android/22571791#22571791 - I know it's in java, but you can get the idea. – elias Mar 22 '14 at 13:08