Day 120クールダウン付きスタックで連打を制限する

2026-06-24 JST ・ 難易度: 実用 ・ カテゴリ: 実用データ構造

Pythonコード

1class CoolDownStack:2    def __init__(self):3        self.stack = []4        self.cool_down_time = 3  # クールダウン時間(秒)5 6    def push(self, item):7        import time8        current_time = time.time()9        if self.stack and current_time - self.stack[-1][1] < self.cool_down_time:10            print("クールダウン中です。しばらくお待ちください。")11            return12        self.stack.append((item, current_time))13 14    def pop(self):15        if not self.stack:16            return None17        return self.stack.pop()[0]18 19# スタックの使用例20stack = CoolDownStack()21while True:22    print("1. プッシュ 2. ポップ 3. 終了")23    try:24        choice = int(input("選択: "))25    except ValueError:26        print("無効な入力です。数字を入力してください。")27        continue28    if choice == 1:29        item = input("アイテム: ")30        stack.push(item)31    elif choice == 2:32        print(stack.pop())33    elif choice == 3:34        break35    else:36        print("無効な選択です。")

解説

次に試してみよう