Advertisement
smj007

Randome Pick with Weight

Aug 11th, 2024
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.79 KB | None | 0 0
  1. class Solution:
  2.  
  3.     def __init__(self, w: List[int]):
  4.         self.w = w
  5.         self.prefixSum = []
  6.         cumSum = 0
  7.         for num in self.w:
  8.             cumSum += num
  9.             self.prefixSum.append(cumSum)
  10.  
  11.  
  12.     def pickIndex(self) -> int:
  13.  
  14.         # imagine there is a stretched number line where a number
  15.         # in w appears as many times as it is the value [1, 3] -> [1, 3, 3, 3]
  16.         target = random.randint(0, sum(self.w) - 1)
  17.         low, high = 0, len(self.w) - 1
  18.         result = len(self.prefixSum) - 1
  19.  
  20.         while (low <= high):
  21.             mid = (low + high) // 2
  22.  
  23.             if target < self.prefixSum[mid]:
  24.                 result = mid
  25.                 high = mid - 1
  26.             else:
  27.                 low = mid + 1
  28.  
  29.         return result
  30.        
  31.  
  32.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement