以下 Python 代码实现了一个简单的理发店模拟,演示了理发师如何处理顾客等待和排队的问题:

class BarberShop:
    def __init__(self, num_chairs):
        self.num_chairs = num_chairs
        self.waiting = []
        self.barber_busy = False

    def enter(self, customer):
        if len(self.waiting) < self.num_chairs:
            self.waiting.append(customer)
            print(f'{customer} entered the shop and is waiting for a haircut.')
        else:
            print(f'{customer} left the shop because there are no available chairs.')
    
    def next_customer(self):
        if self.waiting:
            self.barber_busy = True
            customer = self.waiting.pop(0)
            print(f"The barber is cutting {customer}'s hair.")
            self.barber_busy = False
        else:
            print("The barber is sleeping because there are no customers.")
    
    def is_barber_busy(self):
        return self.barber_busy

class Customer:
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return self.name

if __name__ == '__main__':
    shop = BarberShop(3)
    customers = [Customer('Alice'), Customer('Bob'), Customer('Charlie'), Customer('Dave'), Customer('Eve')]
    for customer in customers:
        shop.enter(customer)
        if not shop.is_barber_busy():
            shop.next_customer()

该代码模拟了以下场景:

  • 当顾客进入理发店时,如果等待室有空位,他们会加入等待队列;
  • 如果等待室已满,顾客会离开;
  • 当理发师有空时,他会为等待队列中的下一个顾客理发;
  • 如果没有顾客在等待,理发师会休息。

代码中的 num_chairs 参数可以控制等待室的椅子数量,从而模拟不同规模的理发店。

这段代码通过简单的逻辑,清晰地展示了理发店管理机制,可以作为学习 Python 编程和解决实际问题的参考。


原文地址: https://www.cveoy.top/t/topic/n7wK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录