Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate non-repeating random numbers in a while loop? (Python 3)

So far what I have is

import random
def go():
    rounds = 0
    while rounds < 5:
        number = random.randint(1, 5)
        if number == 1:
            print('a')
        elif number == 2:
            print('b')
        elif number == 3:
            print('c')
        elif number == 4:
            print('d')
        elif number == 5:
            print('e')
        rounds = rounds + 1
go()

and the output ends up beings something along the lines of

e
e
c
b
e

How do I make it so a number is only used once and the letters do not repeat? (ex. something like)

a
e
b
c
d

Thanks in advance

like image 257
zeurosis Avatar asked Sep 15 '15 22:09

zeurosis


1 Answers

The random.sample(population, k) method returns a sample of unique values from the specified population of length k.

r = random.sample("abcde", 5)
for element in r:
    print(element)
like image 175
asdf Avatar answered Oct 30 '22 05:10

asdf