Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions other/fischer_yates_shuffle.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,19 @@


def fisher_yates_shuffle(data: list) -> list[Any]:
"""
In-place random shuffle of a list using the Fisher–Yates algorithm.

Check failure on line 15 in other/fischer_yates_shuffle.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (RUF002)

other/fischer_yates_shuffle.py:15:55: RUF002 Docstring contains ambiguous `–` (EN DASH). Did you mean `-` (HYPHEN-MINUS)?
The output is a permutation of the input. Since the operation is random,
we assert permutation properties rather than exact order in doctests.
>>> data = [1, 2, 3, 4]
>>> shuffled = fisher_yates_shuffle(data.copy())
>>> sorted(shuffled) == [1, 2, 3, 4]
True
>>> len(shuffled) == len(set(shuffled))
True
"""
for _ in range(len(data)):
a = random.randint(0, len(data) - 1)
b = random.randint(0, len(data) - 1)
Expand Down
28 changes: 26 additions & 2 deletions other/linear_congruential_generator.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,21 @@
"""
Linear Congruential Generator (LCG)
https://en.wikipedia.org/wiki/Linear_congruential_generator

This module implements a simple linear congruential generator. It is intended
for educational purposes, not for cryptographic use.

>>> lcg = LinearCongruentialGenerator(2, 3, 9, seed=1)
>>> [lcg.next_number() for _ in range(5)]
[5, 4, 2, 7, 8]

The generated values are always in the half-open interval [0, modulo):

>>> lcg = LinearCongruentialGenerator(2, 3, 9, seed=1)
>>> all(0 <= lcg.next_number() < 9 for _ in range(10))
True
"""

__author__ = "Tobias Carryer"

from time import time
Expand Down Expand Up @@ -28,9 +46,15 @@ def __init__(self, multiplier, increment, modulo, seed=int(time())): # noqa: B0

def next_number(self):
"""
Generate the next number in the sequence.

The smallest number that can be generated is zero.
The largest number that can be generated is modulo-1. modulo is set in the
constructor.
The largest number that can be generated is ``modulo - 1``. ``modulo`` is
set in the constructor.

>>> lcg = LinearCongruentialGenerator(5, 1, 16, seed=0)
>>> [lcg.next_number() for _ in range(4)]
[1, 6, 15, 12]
"""
self.seed = (self.multiplier * self.seed + self.increment) % self.modulo
return self.seed
Expand Down
Loading