Python/other/fischer_yates_shuffle.py

25 lines
670 B
Python
Raw Normal View History

#!/usr/bin/python
# encoding=utf8
"""
The FisherYates shuffle is an algorithm for generating a random permutation of a finite sequence.
For more details visit
wikipedia/Fischer-Yates-Shuffle.
"""
import random
2019-10-05 05:14:13 +00:00
def FYshuffle(LIST):
for i in range(len(LIST)):
2019-10-05 05:14:13 +00:00
a = random.randint(0, len(LIST) - 1)
b = random.randint(0, len(LIST) - 1)
LIST[a], LIST[b] = LIST[b], LIST[a]
return LIST
2019-10-05 05:14:13 +00:00
if __name__ == "__main__":
integers = [0, 1, 2, 3, 4, 5, 6, 7]
strings = ["python", "says", "hello", "!"]
print("Fisher-Yates Shuffle:")
print("List", integers, strings)
print("FY Shuffle", FYshuffle(integers), FYshuffle(strings))