9 ms·
What you've described is essentially the Fisher-Yates shuffle implemented slowly (O(n²) implementation). The O(n) implementation would be: deck = range(52)
by jcranmer 10y ago
What you've described is essentially the Fisher-Yates shuffle implemented slowly (O(n²) implementation). The O(n) implementation would be:
deck = range(52)
for i in range(len(deck) - 1, 0, -1):
j = random.randint(0, i)
deck[i], deck[j] = deck[j], deck[i]
Intuitively, what the latter implementation is doing is keeping the sorted_deck and shuffled_deck variables in the same array, moving the partition each iteration. The big problem with this method is that it is very easy to make a mistake in its implementation, and any slight mistake will lead to horribly biased outputs.