2018-10-19 15:58:21 +08:00
|
|
|
|
#!/usr/bin/python
|
|
|
|
|
"""
|
2020-06-16 16:09:19 +08:00
|
|
|
|
The Fisher–Yates shuffle is an algorithm for generating a random permutation of a
|
|
|
|
|
finite sequence.
|
2018-05-19 19:07:24 +08:00
|
|
|
|
For more details visit
|
|
|
|
|
wikipedia/Fischer-Yates-Shuffle.
|
2018-10-19 15:58:21 +08:00
|
|
|
|
"""
|
2018-05-19 19:07:24 +08:00
|
|
|
|
import random
|
2021-11-07 18:14:42 +08:00
|
|
|
|
from typing import Any
|
2018-05-19 19:07:24 +08:00
|
|
|
|
|
2019-10-05 13:14:13 +08:00
|
|
|
|
|
2021-11-07 18:14:42 +08:00
|
|
|
|
def fisher_yates_shuffle(data: list) -> list[Any]:
|
|
|
|
|
for _ in range(len(data)):
|
|
|
|
|
a = random.randint(0, len(data) - 1)
|
|
|
|
|
b = random.randint(0, len(data) - 1)
|
|
|
|
|
data[a], data[b] = data[b], data[a]
|
|
|
|
|
return data
|
2018-05-19 19:07:24 +08:00
|
|
|
|
|
2019-10-05 13:14:13 +08: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)
|
2021-08-29 02:07:10 +08:00
|
|
|
|
print("FY Shuffle", fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
|