Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- import bisect
- class ObjectsGenerator:
- def __init__(self, pairs):
- self.max_int = 0
- self.diapasons = self.compute_diapasons(pairs)
- def compute_diapasons(self, pairs):
- diapasons = []
- last_end = 0
- for obj, coeff in pairs:
- current_begin = last_end
- last_end = current_begin + coeff - 1
- diapasons.append((current_begin, last_end, obj))
- last_end += 1
- self.max_int = last_end - 1 if pairs else 0
- return diapasons
- def generate_fast(self):
- if len(self.diapasons) == 1:
- return self.diapasons[0]
- bottoms = [x[0] for x in self.diapasons]
- value = random.randint(0, self.max_int)
- print(value)
- return self.diapasons[bisect.bisect_right(bottoms, value) - 1][2]
- def test_single_element():
- pairs = [('a', 10)]
- gen = ObjectsGenerator(pairs)
- print(gen.generate_fast())
- def test_elements_pair():
- pairs = [('a', 10), ('b', 1)]
- gen = ObjectsGenerator(pairs)
- print(gen.generate_fast())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement