Advertisement
Guest User

Untitled

a guest
Dec 13th, 2017
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.16 KB | None | 0 0
  1. import random
  2. import bisect
  3.  
  4.  
  5. class ObjectsGenerator:
  6.     def __init__(self, pairs):
  7.         self.max_int = 0
  8.         self.diapasons = self.compute_diapasons(pairs)
  9.        
  10.    
  11.     def compute_diapasons(self, pairs):
  12.         diapasons = []
  13.        
  14.         last_end = 0
  15.         for obj, coeff in pairs:
  16.             current_begin = last_end
  17.             last_end = current_begin + coeff - 1
  18.             diapasons.append((current_begin, last_end, obj))
  19.             last_end += 1
  20.            
  21.         self.max_int = last_end - 1 if pairs else 0
  22.         return diapasons
  23.        
  24.     def generate_fast(self):
  25.         if len(self.diapasons) == 1:
  26.             return self.diapasons[0]
  27.  
  28.         bottoms = [x[0] for x in self.diapasons]                
  29.         value = random.randint(0, self.max_int)
  30.         print(value)
  31.         return self.diapasons[bisect.bisect_right(bottoms, value) - 1][2]
  32.        
  33.  
  34. def test_single_element():
  35.     pairs = [('a', 10)]
  36.     gen = ObjectsGenerator(pairs)
  37.     print(gen.generate_fast())
  38.  
  39.  
  40. def test_elements_pair():
  41.     pairs = [('a', 10), ('b', 1)]
  42.     gen = ObjectsGenerator(pairs)
  43.     print(gen.generate_fast())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement