Pythonでクラスを実装して待ち行列システムをシミュレーションする
Pythonを使用して簡単な待ち行列システムクラスを実装します。このクラスにより、ユーザーは顧客をキューに追加したり、顧客を削除したり、現在のキューの状態を確認したりできます。
実例
class QueueSystem:
def __init__(self):
self.queue = []
def add_customer(self, name):
self.queue.append(name)
print(f"{name} has been added to the queue.")
def remove_customer(self):
if self.queue:
removed_customer = self.queue.pop(0)
print(f"{removed_customer} has been removed from the queue.")
else:
print("The queue is empty.")
def show_queue(self):
if self.queue:
print("Current queue:")
for i, customer in enumerate(self.queue, 1):
print(f"{i}. {customer}")
else:
print("The queue is empty.")
# Example usage
queue_system = QueueSystem()
queue_system.add_customer("Alice")
queue_system.add_customer("Bob")
queue_system.show_queue()
queue_system.remove_customer()
queue_system.show_queue()
def __init__(self):
self.queue = []
def add_customer(self, name):
self.queue.append(name)
print(f"{name} has been added to the queue.")
def remove_customer(self):
if self.queue:
removed_customer = self.queue.pop(0)
print(f"{removed_customer} has been removed from the queue.")
else:
print("The queue is empty.")
def show_queue(self):
if self.queue:
print("Current queue:")
for i, customer in enumerate(self.queue, 1):
print(f"{i}. {customer}")
else:
print("The queue is empty.")
# Example usage
queue_system = QueueSystem()
queue_system.add_customer("Alice")
queue_system.add_customer("Bob")
queue_system.show_queue()
queue_system.remove_customer()
queue_system.show_queue()
コード解析:
QueueSystemクラス初期化時に空のリストを作成しますqueue顧客を格納します。add_customerメソッドは顧客の名前を受け取り、それをキューの末尾に追加します。remove_customerメソッドはキューの最初の顧客(つまり最も早く追加された顧客)を削除し、キューが空の場合はキューが空であることを通知します。show_queueメソッドは現在のキュー内のすべての顧客を表示し、キューが空の場合はキューが空であることを通知します。
出力結果:
Alice has been added to the queue. Bob has been added to the queue. Current queue: 1. Alice 2. Bob Alice has been removed from the queue. Current queue: 1. Bobその他の拡張
Python3 実例