Skip to content

Commit b3a4911

Browse files
committed
feat: add choices func
1 parent a702460 commit b3a4911

1 file changed

Lines changed: 20 additions & 0 deletions

File tree

pycustomrand/random_generator.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,26 @@ def choice(array: list[Any]) -> Any:
153153
index = PseudoRandom.randrange(len(array))
154154
return array[index]
155155

156+
@staticmethod
157+
def choices(array: list[Any], k: int, weights: list[int] = None) -> list[Any]:
158+
"""
159+
Возвращает список из k случайных элементов из массива (с повторениями).
160+
161+
weights - список с весами для каждого элемента массива (соответствует по индексу).
162+
Если None - все элементы считаются равными (по 1 весу).
163+
"""
164+
if weights is None:
165+
weights = [1] * len(array)
166+
167+
if len(array) != len(weights):
168+
raise ValueError("Длина массива и длина weights должны быть равны")
169+
170+
weighted_array = []
171+
for item, weight in zip(array, weights):
172+
weighted_array.extend([item] * weight)
173+
174+
return [PseudoRandom.choice(weighted_array) for _ in range(k)]
175+
156176
@staticmethod
157177
def shuffle(array: list[Any]) -> None:
158178
"""Перемешивает массив на месте."""

0 commit comments

Comments
 (0)