In the shop there are 3 barbers, Alpha, Beta and Gamma, who are not always efficient as employees. All the customers are seated in a waiting area, each customer has a card which has a unique integral ID.Alpha: He will call either the person with least ID from the waiting area of the one with max ID. Min or Max is decided randomly by him (assume 50% probability for each min or max). Beta: He will choose a ‘k’ and will call the kth smallest ID, (Kth ID when all IDs are arranged in ascending order). K is chosen randomly from the number of persons available in waiting area (1<= K <= Total persons)
Gamma: He will always choose the median ID. If there are ‘n’ people in the waiting area, the median will be defined as (n+1)/2 th ID when all of them are arranged in ascending order. (For both odd and even ‘n’ ). design a data structure which should support the query of each of the three barbers.
import random
class Barbershop():
def __init__(self):
self.queue = [] # the queue is always sorted
self.current_id = 1
def enqueue(self):
self.queue.append(self.current_id)
self.current_id += 1
return self.current_id - 1
def call_alpha(self):
if self.queue:
return self.queue.pop(random.choice((0, -1)))
else:
print('No customers')
def call_beta(self):
if self.queue:
return self.queue.pop(random.randrange(0, len(self.queue)))
else:
print('No customers')
def call_gamma(self):
if self.queue:
return self.queue.pop(len(self.queue) // 2)
else:
print('No customers')
# example of use:
barbershop = Barbershop()
barbershop.call_alpha()
print(barbershop.enqueue())
barbershop.call_beta()
print(barbershop.enqueue())
barbershop.call_alpha()
print(barbershop.enqueue())
barbershop.call_gamma()
Comments
Leave a comment