You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python循环队列实现问题:轮流队列的字符串表示与轮次逻辑修复

修复后的循环队列实现

以下是符合需求的循环队列实现,解决了字符串格式错误、无限轮次人员丢失、队列空异常等问题:

class RotatingQueue:
    def __init__(self, people):
        # 初始化队列,存储(name, rounds)元组,确保轮次为整数
        self.queue = [(name, int(rounds)) for name, rounds in people]
    
    def __str__(self):
        # 生成清晰的队列字符串,无限轮次显示为∞
        formatted_items = []
        for name, rounds in self.queue:
            round_str = "∞" if rounds <= 0 else str(rounds)
            formatted_items.append(f"{name}({round_str})")
        return f"Queue: [{', '.join(formatted_items)}]"
    
    def next_person(self):
        # 处理空队列情况,抛出明确异常
        if not self.queue:
            raise ValueError("Queue is empty - no available members to process")
        
        name, rounds = self.queue.pop(0)
        
        # 轮次逻辑处理
        if rounds <= 0:
            # 无限轮次人员,使用后直接重新入队
            self.queue.append((name, rounds))
        else:
            new_rounds = rounds - 1
            # 剩余轮次>0则重新入队,轮次耗尽则移除
            if new_rounds > 0:
                self.queue.append((name, new_rounds))
        
        return name

关键修复点说明

1. 正确的字符串表示

  • 重写__str__方法,遍历队列元素时,将轮次≤0的人员标记为∞,有限轮次显示剩余次数,最终拼接成可读性强的队列格式,比如Queue: [Alice(2), Bob(∞), Charlie(∞)]。

2. 修复轮次逻辑缺陷

  • 保留所有人员的轮次信息:初始化时直接存储原始轮次(包括≤0的无限轮次),不会丢失无限轮次的人员。
  • 无限轮次处理:轮次≤0的人员每次被调用后,直接重新入队,实现无限循环。
  • 有限轮次处理:每使用一次轮次减1,仅当剩余轮次>0时才重新入队,轮次耗尽(减至0)则从队列中移除。

3. 解决队列空异常

  • 在next_person方法开头检查队列是否为空,若为空则抛出ValueError并给出明确提示,避免弹出空队列导致的索引错误。

测试用例验证

if __name__ == "__main__":
    # 初始化测试队列
    rq = RotatingQueue([("Alice", 2), ("Bob", 0), ("Charlie", 1), ("Dave", -1)])
    print(rq)  # 输出: Queue: [Alice(2), Bob(∞), Charlie(1), Dave(∞)]
    
    # 依次调用验证逻辑
    print(rq.next_person())  # Alice → 剩余轮次1,重新入队
    print(rq)  # Queue: [Bob(∞), Charlie(1), Dave(∞), Alice(1)]
    
    print(rq.next_person())  # Bob → 无限轮次,重新入队
    print(rq)  # Queue: [Charlie(1), Dave(∞), Alice(1), Bob(∞)]
    
    print(rq.next_person())  # Charlie → 轮次减至0,不再入队
    print(rq)  # Queue: [Dave(∞), Alice(1), Bob(∞)]
    
    print(rq.next_person())  # Dave → 无限轮次,重新入队
    print(rq)  # Queue: [Alice(1), Bob(∞), Dave(∞)]
    
    print(rq.next_person())  # Alice → 轮次减至0,不再入队
    print(rq)  # Queue: [Bob(∞), Dave(∞)]
    
    # 验证无限轮次循环
    print(rq.next_person())  # Bob
    print(rq.next_person())  # Dave
    print(rq.next_person())  # Bob
    print(rq)  # Queue: [Dave(∞), Bob(∞)]

内容的提问来源于stack exchange,提问作者BRN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 06:35:20