Python类列表问题

Python类列表问题,python,python-3.x,Python,Python 3.x,我被赋予了一项实现堆栈数据结构的任务,并被赋予了我必须处理的基本代码。该任务的目的是让用户将数据输入到堆栈列表中,并且限制为6个输入 当我运行测试程序时,选项菜单按预期显示,我输入数据,它返回“True”。然而,无论我不断地添加多少数据,它总是会返回“True”,我不明白为什么?将6个元素添加到列表中后,应该会返回一条错误消息 主程序: class Stack: def __init__(self): self.stack = list() self.S

我被赋予了一项实现堆栈数据结构的任务,并被赋予了我必须处理的基本代码。该任务的目的是让用户将数据输入到堆栈列表中,并且限制为6个输入

当我运行测试程序时,选项菜单按预期显示,我输入数据,它返回
“True”
。然而,无论我不断地添加多少数据,它总是会返回“True”,我不明白为什么?将6个元素添加到列表中后,应该会返回一条错误消息

主程序:

class Stack:

    def __init__(self):
        self.stack = list()
        self.StackSize = 5
        self.top = 0

    def push(self,data):
        #if there is room on the stack, add a new item to the end
        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 stack is not empty, return last item
        if self.top <= 0:
            return ("Error! Error! Unable to perform function! Stakc is empty! Stack is empty!")
        item = self.stack.pop()
        self.top -= 1
        return item

    def isEmpty(self):
        if self.stack == []:
            return True
        else:
            return False

    def isFull(self):
        if len(self.stack) == StackSize:
            return True
        else:
            return False
    
    def top(self):
        if self.stack:
            return self.stack[-1]
        else:
            return ("Stack is empty.")

    def getStack(self):
        return("Stack: " + self.stack)
您的
main()
方法调用一个新的
main()
函数。这将创建一个新的
堆栈
对象。基本上总是重置堆栈。例如,在函数外部创建堆栈

s = Stack()

def main():
    # code as normal
祝你的家庭作业好运,问题就在这里

def main():

s = Stack()
调用main函数时,创建一个新堆栈。无论何时选择一个选项,都会再次调用main函数

elif choice == "2":
print(s.pop())
main()# here
这将创建一个新堆栈,其中大小将再次为0。由于这可能是一项学习任务,我将仅解释如何解决此问题

  • 将堆栈放入参数中
  • 在函数外部创建堆栈
  • 使用while循环,而不是递归

  • 每次选择可接受的选项时,都会调用
    main()
    。通过这样做,您正在实例化另一个
    堆栈
    对象,根据定义,该对象为空。由于您继续调用
    main()
    ,堆栈将永远不会满,但您将拥有
    nummaincall
    stack
    s,每个堆栈最多包含
    1
    元素

    我建议您定义一个调用子例程的主函数,您可以通过传递
    堆栈
    对象在其中循环:

    def main:
        s = Stack()
        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: ")
    
        while True:
            choice = input("\nPlease enter your choice: ")
            execute_subroutine(s, choice)
            if choice == "7":
                break
    
    
    def execute_subroutine(s, choice):
        if choice not in ["1", "2", "3", "4", "5", "6", "7"]:
            print("\nInvalid entry. Please select from the menu provided.")
        else:
            if choice == "1":
                x = ""
                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.top())
    
            elif choice == "6":
                print(s.getStack())
    
            else:
                print ("Ending Program")
            
    

    这样你就能得到你想要的。请注意,我的代码可能有一些小问题,因为目前我无法测试它。无论如何,它应该是正确的。

    使用循环而不是递归。每次递归调用
    main()
    都会创建一个新的
    Stack
    实例。非常感谢您的评论,非常感谢!非常感谢您的评论,非常感谢!非常感谢您的评论,非常感谢!
    def main:
        s = Stack()
        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: ")
    
        while True:
            choice = input("\nPlease enter your choice: ")
            execute_subroutine(s, choice)
            if choice == "7":
                break
    
    
    def execute_subroutine(s, choice):
        if choice not in ["1", "2", "3", "4", "5", "6", "7"]:
            print("\nInvalid entry. Please select from the menu provided.")
        else:
            if choice == "1":
                x = ""
                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.top())
    
            elif choice == "6":
                print(s.getStack())
    
            else:
                print ("Ending Program")