Answer to Question #229893 in Python for Raaj

Question #229893

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.


1
Expert's answer
2021-08-26T07:45:02-0400
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()

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS