28
loading...
This website collects cookies to deliver better user experience
class Shape:
def __init__(self, name, chances):
self.name = name
self.chances = chances
shapes = [
Shape("ZigZag", 8),
Shape("LeftZigZag", 8),
Shape("L", 4),
Shape("LeftL", 4),
Shape("Square", 2),
Shape("Line", 1),
]
27
. So the chances of getting a ZigZag will be 8 out of 27, when the chances of getting a line would be 1 out of 27.class RandomShapePicker:
def __init__(self, shapes):
self.chances = []
for shape in shapes:
for _ in range(shape.chances):
self.chances.append(shape)
def pick_shape(self):
return random.choice(self.chances)
RandomShapePicker
, memory will be in function of the total sum of chances (In this case 27) and the time complexity will be in function of the sum of chances as well: O(C), where C is the total sum of chances
.O(1)
.pick_shape
multiple times as we can expect constant time for these calls.chances
. Imagine that the sum of chances is 1000000 which means that our list should have 1M spots. Even if the different choices are low (Let's say 1000).self.chances = [8, 16, 20, 24, 26, 27]
insertion point
for that random number, and then select the shape based on the chances that we have to get that shape:class RandomShapePicker:
def __init__(self, shapes):
self.shapes = shapes
self.chances = []
self.total_chances = 0
for shape in shapes:
self.total_chances += shape.chances
self.chances.append(self.total_chances)
def pick_shape(self):
choice = random.random() * self.total_chances
i = bisect_left(self.chances, choice)
return self.shapes[i]
RandomShapePicker
creation.O(N)
time and space complexity (N is the number of choices which is less than number of chances), and pick_shape time complexity is now O(logN)
which is still a decent performance for multiple callings of pick_shape.