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

编程新手求助:如何为ArrayStack实现添加maxlen容量限制功能?

How to Modify ArrayStack with Max Capacity and Full Exception

Hey there! Since you're new to programming, let's walk through this task clearly, step by step. I'll assume you already have a basic ArrayStack implementation with the Empty exception defined—we'll build directly on that foundation.

Step 1: Define the Full Exception

First, we need a custom Full exception that mirrors the existing Empty one. It's straightforward, just inherit from Python's built-in Exception:

class Empty(Exception):
    """Error attempting to access an element from an empty stack."""
    pass

class Full(Exception):
    """Error attempting to push an element to a full stack."""
    pass

Step 2: Update the Constructor with maxlen Parameter

Modify the ArrayStack's __init__ method to accept an optional maxlen parameter (defaulting to None, which means no capacity limit). We'll store this value as an instance variable alongside our underlying data array:

class ArrayStack:
    def __init__(self, maxlen=None):
        self._data = []
        self._maxlen = maxlen  # Store the capacity limit for later checks

Step 3: Modify the push Method to Enforce Capacity Limits

Now, update the push method to check if the stack is full before adding a new element. If maxlen is None, we skip the check (keeping the original unlimited behavior). If maxlen is set and the stack's current length matches it, we raise the Full exception:

def push(self, e):
        # Only check capacity if maxlen is defined
        if self._maxlen is not None and len(self._data) >= self._maxlen:
            raise Full("Stack has reached maximum capacity")
        self._data.append(e)

Optional: Add an is_full Helper Method

For convenience, you can add a helper method to let callers check if the stack is full without triggering an exception. This is useful for graceful handling of full cases:

def is_full(self):
        # Unlimited capacity stacks are never full
        if self._maxlen is None:
            return False
        return len(self._data) >= self._maxlen

Example Usage

Let's test this implementation to make sure it works as expected:

# Stack with no capacity limit (default behavior)
unlimited_stack = ArrayStack()
for i in range(100):
    unlimited_stack.push(i)  # No exceptions raised

# Stack with max capacity of 5
limited_stack = ArrayStack(maxlen=5)
for i in range(5):
    limited_stack.push(i)  # Works perfectly

limited_stack.push(6)  # Raises Full exception: Stack has reached maximum capacity

That's all! Each part builds on the basic stack you already have, and follows the requirements exactly. If you hit any snags with your existing code, feel free to share snippets and we can troubleshoot together.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:12:28