mirror of
https://github.com/TheAlgorithms/Python.git
synced 2026-09-28 21:45:27 +08:00
* Added some Unit Tests to increase test code coverage * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * updating DIRECTORY.md --------- Co-authored-by: TheRealHaui <michael.hausegger@hausegger.tech> Co-authored-by: Christian Clauss <cclauss@me.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: pre-commit-ci[bot] <pre-commit-ci[bot]@users.noreply.github.com>
34 lines
986 B
Python
34 lines
986 B
Python
#!/usr/bin/python
|
|
"""
|
|
The Fisher-Yates shuffle is an algorithm for generating a random permutation of a
|
|
finite sequence.
|
|
For more details visit
|
|
wikipedia/Fischer-Yates-Shuffle.
|
|
"""
|
|
|
|
import random
|
|
from typing import Any
|
|
|
|
|
|
def fisher_yates_shuffle(data: list) -> list[Any]:
|
|
"""
|
|
>>> import random
|
|
>>> from unittest.mock import patch
|
|
>>> with patch('random.randint', side_effect=[0, 3, 1, 2, 2, 0, 3, 1]):
|
|
... fisher_yates_shuffle(["python", "says", "hello", "!"])
|
|
['says', 'python', '!', 'hello']
|
|
"""
|
|
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
|
|
|
|
|
|
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", fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
|