python - 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")
解决方案
每次您选择一个可接受的选项时,您总是调用main()
. 通过这样做,您正在实例化另一个Stack
根据定义为空的对象。由于您继续调用main()
,因此您的堆栈将永远不会满,但您将拥有numMainCalls
多个Stack
s,每个 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")
这样你应该能够得到你想要的。请注意,我的代码可能存在一些小问题,因为目前我无法对其进行测试。无论如何,它应该是正确的。
推荐阅读
- mysql - 如何使用 Perl Net::MySQL 更新和删除记录
- java - 如何通过 BLE 从 Android APP 向 BLE Reciever 发送数据?
- php - 如何使用 laravel 5.7 在邮件降价的表格单元格中显示图像?
- javascript - 在 Vue.js 单文件组件中使用 jQuery 插件
- dart - Flutter 中的音频播放器插件 - 无法加载资产
- c# - aspboilerplate 中的权限管理
- python-3.x - 如何在夹具中导入 python 并将它们用作 Pytest 中每个测试的全局变量?
- java - 如何使用 netcat 将 Cassandra 查询的整个结果发送到套接字
- android - how can i communicate to google home mini device with android app or vise-versa
- python - Python tkinter Menu