Skip to content

Commit a702460

Browse files
committed
feat: add sample func
1 parent 9f59d2f commit a702460

1 file changed

Lines changed: 29 additions & 0 deletions

File tree

pycustomrand/random_generator.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,3 +161,32 @@ def shuffle(array: list[Any]) -> None:
161161
x1 = PseudoRandom.randrange(limit)
162162
x2 = PseudoRandom.randrange(limit)
163163
array[x1], array[x2] = array[x2], array[x1]
164+
165+
@staticmethod
166+
def sample(array: list[Any], k: int, counts: list[int] = None) -> list[Any]:
167+
"""
168+
Возвращает список из k уникальных случайных элементов из массива.
169+
170+
counts - список с количеством повторений для каждого элемента массива (соответствует по индексу).
171+
Если None - все элементы считаются равными (по 1 повторению).
172+
"""
173+
if counts is None:
174+
counts = [1] * len(array)
175+
176+
if len(array) != len(counts):
177+
raise ValueError("Длина массива и длина counts должны быть равны")
178+
179+
weighted_array = []
180+
for item, count in zip(array, counts):
181+
weighted_array.extend([item] * count)
182+
183+
if k > len(set(weighted_array)):
184+
raise ValueError("k не может быть больше количества уникальных элементов в массиве с учётом counts")
185+
186+
result = []
187+
while len(result) < k:
188+
choice = PseudoRandom.choice(weighted_array)
189+
if choice not in result:
190+
result.append(choice)
191+
192+
return result

0 commit comments

Comments
 (0)