We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent a34df7a commit 7c072c6Copy full SHA for 7c072c6
scripts/algorithms/R/Random Pick with Weight/Random Pick with Weight.py
@@ -1,12 +1,24 @@
1
class Solution(object):
2
+ def __init__(self, w):
3
+ """
4
+ :type w: List[int]
5
6
+ #Cumulative sum
7
+ self.list = [0] * len(w)
8
- def __init__(self, w):
- self.preSums = [w[0]]
- for i in range(1, len(w)):
- self.preSums.append(self.preSums[-1] + w[i])
-
9
+ s = 0
10
+ for i, n in enumerate(w):
11
+ s += n
12
+ self.list[i] = s
13
- def pickIndex(self):
- x = random.randint(1, self.preSums[-1])
- index = bisect_left(self.preSums, x)
- return index
14
+
15
+ def pickIndex(self):
16
17
+ :rtype: int
18
19
+ return bisect_left(self.list, random.randint(1, self.list[-1]))
20
21
22
+# Your Solution object will be instantiated and called as such:
23
+# obj = Solution(w)
24
+# param_1 = obj.pickIndex()
0 commit comments