Skip to content

Commit 9e1ff4d

Browse files
Use python's implementations for random_weighted_choice
The existing implementation looked buggy. It was fine but let's use Python's stdlib implementation so we can be more sure.
1 parent 8da25b5 commit 9e1ff4d

File tree

1 file changed

+2
-13
lines changed

1 file changed

+2
-13
lines changed

src/clusterfuzz/_internal/base/utils.py

Lines changed: 2 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -599,21 +599,10 @@ def random_number(start, end):
599599
return random.SystemRandom().randint(start, end)
600600

601601

602-
# pylint: disable=inconsistent-return-statements
603602
def random_weighted_choice(element_list, weight_attribute='weight'):
604603
"""Returns a random element from list taking its weight into account."""
605-
total = sum(getattr(e, weight_attribute) for e in element_list)
606-
random_pick = random.SystemRandom().uniform(0, total)
607-
temp = 0
608-
for element in element_list:
609-
element_weight = getattr(element, weight_attribute)
610-
if element_weight == 0:
611-
continue
612-
if temp + element_weight >= random_pick:
613-
return element
614-
temp += element_weight
615-
616-
assert False, 'Failed to make a random weighted choice.'
604+
weights = [getattr(element, weight_attribute) for element in element_list]
605+
return random.SystemRandom().choices(element_list, weights, k=1)[0]
617606

618607

619608
def read_data_from_file(file_path, eval_data=True, default=None):

0 commit comments

Comments
 (0)