From 2efadbb88320d468e1ab49f1d954bc09dac239f6 Mon Sep 17 00:00:00 2001 From: Jack Sangdahl Date: Mon, 23 Jun 2025 00:00:56 -0600 Subject: 528. random pick with weight --- random_pick_weight.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 random_pick_weight.py (limited to 'random_pick_weight.py') diff --git a/random_pick_weight.py b/random_pick_weight.py new file mode 100644 index 0000000..3eda7fd --- /dev/null +++ b/random_pick_weight.py @@ -0,0 +1,36 @@ +# 528. Random Pick with Weight +from itertools import accumulate +from bisect import bisect_left +from random import randint + +""" +you are given a 0-indexed array of positive integers 'w' where 'w[i]' +describes the weight of the i'th index. you need to implement the function +'pickIndex()' which randomly picks an index in the range '[0, w.len - 1]' and +returns it. the probability of picking an index 'i' is 'w[i] / sum(w)'. +""" + + +class Solution(object): + def __init__(self, w): + """ + :type w: List[int] + """ + self.w = list(accumulate(w)) + + def pickIndex(self): + """ + :rtype: int + """ + return bisect_left(self.w, randint(1, self.w[-1])) + + +if __name__ == "__main__": + obj1 = Solution([1]) + obj2 = Solution([1, 3]) + print(obj1.pickIndex()) + print(obj1.pickIndex()) + print(obj1.pickIndex()) + print(obj1.pickIndex()) + print(obj1.pickIndex()) + print(obj1.pickIndex()) -- cgit v1.2.3