我在 Python (以及一般编程)方面很新,试图实现一个堆栈类,它具有一个函数来在堆栈中的任何位置 p '插入'一个值 v (即使考虑到它是一个堆栈它很奇怪)。这是我的堆栈类:
class Stack:
def __init__(self, maxSize):
self.stack = list([])
self.maxSize = maxSize
self.size = int(0)
这是我插入值的函数:
def addValToPos(self, position, value):
temporaryList = [] # i tried to make a temporary list for every time the function was called
for i in range(len(self.stack)):
if i > position-1:
temporaryList += self.stack[i]
while self.size > position:
self.pop() #removes the last position in stack (LIFO)
self.push(value)
for j in range(len(temporaryList)):
self.stack += temporaryList[j]
#del temporarylist <-- tried to delete the list in the end of the function
当我尝试执行该功能时,它第一次起作用,但第二次不起作用(因为我无法删除临时列表)。我认为最好temoraryList在函数中创建一个,然后在之后删除它
对此有什么想法,或者我应该如何在将temporaryList它们添加回之后删除变量,self.stack以便它们在添加变量之后出现?这是我的函数调用:
maxSize = int(input("Enter max size: "))
stabel = Stack(maxSize)
while stabel.size != stabel.maxSize:
value = input("Enter value: ")
stabel.push(value)
stabel.print()
while True:
if stabel.size < stabel.maxSize:
que = input("Add value to pos? (yes/no)")
if que.lower() == 'yes':
position = int(input("Add position p: "))
valToPos = int(input("Add value v: "))
stabel.addValToPos(position-1, valToPos)
stabel.size += 1
else:
break
elif stabel.size >= stabel.maxSize:
question0 = input("Increase the max size? (yes/no)")
if question0.lower() == 'yes':
addToMax0 = input("How much?")
stabel.increase(addToMax0)
else:
break
stabel.print()
stabel.showSize()
print("Maxsize: ", stabel.maxSize)
此外,在第一次通过 while 循环之后,它似乎没有检查是否self.size小于self.maxSize. 也查不出来。顺便说一句,如果代码难以阅读,我很抱歉,我在粘贴时遇到了一些麻烦。
蛊毒传说
郎朗坤
大话西游666
相关分类