Skip to content

Instantly share code, notes, and snippets.

@m00nlight
Last active April 18, 2018 10:13
Show Gist options
  • Save m00nlight/b3f7a4e4fb9ee9ddd1dd to your computer and use it in GitHub Desktop.
Save m00nlight/b3f7a4e4fb9ee9ddd1dd to your computer and use it in GitHub Desktop.
Python Knuth shuffle algorithm
def knuth_shuffle(items):
"""
Fisher-Yates shuffle or Knuth shuffle which name is more famous.
See <http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle> for detail
Type : [a] -> None (shuffle inplace)
Post constrain: Should be list
Post constrain: return array of the same length of input
"""
for i in range(len(items)):
j = randrange(i, len(items))
items[i], items[j] = items[j], items[i]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment