首页 > 解决方案 > Python Class List Issue

问题描述

I've been given a task of implementing a Stack data structure and was given basic code that I had to work on. The aim of the task is to get the user to input data into the stack list and it is limited to 6 inputs.

When I run the test program, the menu of options appears as expected and I enter in the data and it returns "True". However, it doesn't matter how much data I continually add in, it will always come back "True" and I'm not understanding why? After 6 elements have been added to the list, it should come back with an error message.

Main Program:

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)

Test Program:

from Stack import 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: ")
    #Error handler to cope with an 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 = ""
        x = input("Add an element to the stack: ")
        print(s.push(x))
        main()

    elif choice == "2":
        print(s.pop())
        main()

    elif choice == "3":
        print(s.isEmpty())
        main()

    elif choice == "4":
        print(s.isFull())
        main()

    elif choice == "5":
        print(s.top())

    elif choice == "6":
        print(s.getStack())

    else:
        print ("Ending Program")

标签: pythonpython-3.x

解决方案


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

我建议您定义一个调用子例程的主函数,您可以通过传递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")
        

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


推荐阅读