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

Python栈实现异常:超出容量限制仍返回True未触发栈满错误

Fixing Your Stack Implementation Issues

Let's break down and fix all the bugs in your Stack code that are causing it to never report being full, plus address other related problems:

Key Bugs Causing the "Never Full" Problem

  • Wrong capacity value: You want a stack that holds up to 6 elements, but you set self.StackSize = 5. Since top starts at 0 and increments after each push, this limits your stack to 5 elements max. Change this to self.StackSize = 6 to allow 6 elements.
  • Broken isFull() method: The method uses StackSize instead of self.StackSize (it's an instance attribute, not a global/class variable). This would throw a NameError if called. Also, using self.top == self.StackSize is more efficient than checking len(self.stack).
  • Method-attribute name conflict: You have a self.top integer attribute and a def top(self) method. This overwrites the attribute, making the method unusable and causing errors when trying to access the top element. Rename the method to peek() or get_top().

Other Fixes Needed

  • Broken getStack(): You can't concatenate a list directly to a string. Convert the stack to a string first with str().
  • Typo in error message: The pop() method has a typo: "Stakc is empty" should be "Stack is empty".
  • Recursion in test program: Calling main() after each operation will cause a recursion depth error with repeated use. Replace recursion with a loop.

Corrected Stack Class

class Stack:
    def __init__(self):
        self.stack = list()
        self.StackSize = 6  # Updated to hold 6 elements
        self.top = 0

    def push(self, data):
        if self.top >= self.StackSize:
            return "Error! Error! Unable to perform function! Stack is full! Stack is full!"
        self.stack.append(data)
        self.top += 1
        return True

    def pop(self):
        if self.top <= 0:
            return "Error! Error! Unable to perform function! Stack is empty! Stack is empty!"  # Fixed typo
        item = self.stack.pop()
        self.top -= 1
        return item

    def isEmpty(self):
        return self.top == 0  # More efficient than checking list emptiness directly

    def isFull(self):
        return self.top == self.StackSize  # Fixed attribute access and logic

    def peek(self):  # Renamed from top() to avoid conflict
        if self.top > 0:
            return self.stack[-1]
        else:
            return "Stack is empty."

    def getStack(self):
        return "Stack: " + str(self.stack)  # Converted list to string

Corrected Test Program

from Stack import Stack

def main():
    s = Stack()
    while True:
        print ("--- Menu of Options ---")
        print ("1: Add An Element To The Stack")
        print ("2: Remove The Top Element From The Stack")
        print ("3: Report Whether The Stack Is Empty")
        print ("4: Report Whether The Stack Is Full")
        print ("5: View The Top Element Of The Stack")
        print ("6: View The Entire Contents Of The Stack")
        print ("7: Exit Program")
        
        choice = input("\nPlease enter your choice: ")
        # Error handler for invalid choice
        while not choice in ("1", "2", "3", "4", "5", "6", "7"):
            print("\nInvalid entry. Please select from the menu provided.")
            choice = input ("\nPlease enter your choice: ")
        
        if choice == "1":
            x = input("Add an element to the stack: ")
            print(s.push(x))
        elif choice == "2":
            print(s.pop())
        elif choice == "3":
            print(s.isEmpty())
        elif choice == "4":
            print(s.isFull())
        elif choice == "5":
            print(s.peek())  # Updated to use renamed method
        elif choice == "6":
            print(s.getStack())
        else:
            print ("Ending Program")
            break  # Exit the loop instead of recursion

if __name__ == "__main__":
    main()

Now when you push 6 elements, the 7th push will return the stack full error, and the isFull() method will correctly return True once the stack is at capacity.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 14:47:33