-2

Fisher–Yates shuffle means that we take the last number from the selected segment every time and swap it with the previously randomly selected number, iterate continuously, and finally achieve random shuffling.The code for the official Shuffle in python3.6 is as follows

     _int = int
     for i in reversed(range(1, len(x))):
          # pick an element in x[:i+1] with which to exchange x[i]
          j = _int(random() * (i+1))
          x[i], x[j] = x[j], x[i]

Why not just pick the global locations and swap?

3
  • "then the position to be exchanged is always 0 every time the random selection is made" - no it's not. Sep 30, 2021 at 4:06
  • what's the reason for _int = int?
    – Barmar
    Sep 30, 2021 at 4:10
  • 1
    @Barmar: It's a microoptimization to avoid some global lookups. Not as impactful these days due to global variable caching optimizations. Sep 30, 2021 at 4:14

1 Answer 1

2

random() is a float in the range [0, 1). When you multiply that by i+1, you get a float in the range [0, i+1). When you convert that to an integer, you get an integer in the range [0, i].

Of course, you could just use random.randint(0, i). And reverse(range(1, len(x)) can be simplified to range(len(x)-1, 0, -1).

1
  • The code does in fact avoid using random() in the usual code path - what the questioner posted was an alternate code path used if the caller provides their own random argument. It uses randbelow in the usual case. (As for "simplifying" reversed(range(1, len(x)), that's a matter of opinion. I personally find the reversed version much clearer.) Sep 30, 2021 at 4:15

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.