David Srinivasan
David Srinivasan

Reputation: 3

Random choice without repeats

I need to generate a unique element each time random choice is run without any repeats each time its run (lists are not allowed to be used ) eg : (x,y,z) (y,x,z) (z,y,x)


from random import choice
operator=random.choice("xyz")

Upvotes: 0

Views: 110

Answers (2)

user16836078
user16836078

Reputation:

According to your example, you're trying to do permutations to find unique elements?

from itertools import permutations

for i in permutations("xyz"):
    print (i)

('x', 'y', 'z')
('x', 'z', 'y')
('y', 'x', 'z')
('y', 'z', 'x')
('z', 'x', 'y')
('z', 'y', 'x')

Upvotes: 2

Bill
Bill

Reputation: 11643

Is this what you are looking for:

import random

for i in range(5):
    print(random.sample("xyz", 3))

['y', 'z', 'x']
['z', 'y', 'x']
['z', 'x', 'y']
['x', 'y', 'z']
['z', 'x', 'y']

I think this is an equivalent solution:

for i in range(5):
    x = list("xyz")
    random.shuffle(x)
    print(x)

Upvotes: 1

Related Questions