File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff 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 """Перемешивает массив на месте."""
You can’t perform that action at this time.
0 commit comments