Come funziona Python random shuffle?

8

In che modo shuffle da random funziona in Python?

Chiedo perché funziona molto velocemente. Quando provo a scrivere shuffle funziona 1 minuto per 10 ^ 6 elementi, ma Python shuffle lo fa in 8 secondi?

    
posta Paweł Szymański 28.10.2013 - 09:29
fonte

1 risposta

15

Il random.shuffle di Python utilizza Fisher-Yates shuffle , che viene eseguito in tempo O (n) e si è dimostrato un perfetto shuffle (presupponendo un buon generatore di numeri casuali) .

itera l'array dall'ultima alla prima voce, cambiando ogni voce con una voce in un indice casuale sotto di essa.

The basic process of Fisher–Yates shuffling is similar to randomly picking numbered tickets out of a hat, or cards from a deck, one after another until there are no more left. What the specific algorithm provides is a way of doing this numerically in an efficient and rigorous manner that, properly done, guarantees an unbiased result...

The modern... solution is to move the "struck" numbers to the end of the list by swapping them with the last unstruck number at each iteration. This reduces the algorithm's time complexity to O(n), compared to O(n2) for the naive implementation. This change gives the following algorithm (for a zero-based array).

To shuffle an array a of n elements (indices 0..n-1):
  for i from n − 1 downto 1 do
       j ← random integer with 0 ≤ j ≤ i
       exchange a[j] and a[i]
    
risposta data 30.09.2015 - 16:52
fonte

Leggi altre domande sui tag