Reputation: 51
I just wanted to know if there's a way to stop the random.sample from generating the same combination again in list.
So for example combination [4, 6, 1] already appeared in random.sample then I don't want it to appear again to make the matching of my variable code faster.
Thanks
import random
code = [2, 6, 4]
while True:
rand = random.sample(range(0, 10), 3)
if(rand == code):
print(str(rand) + " access granted")
break
else:
print(str(rand) + "access denied")
Upvotes: 1
Views: 98
Reputation: 51998
There are only 10 * 9 * 8 = 720
possible distinct guesses. If you don't want to make the same guess twice, build up a list of all possible guesses (easy to do with nested loops, but even easier to do with itertoools), shuffle that list, and then iterate over it. One implementation:
import random, itertools
code = [2, 6, 4]
guesses = [list(p) for p in itertools.permutations(range(10),3)]
random.shuffle(guesses)
for guess in guesses:
if(guess == code):
print(guess, "access granted")
break
else:
print(guess, "access denied")
Upvotes: 2