[英]I can only push two values onto the stack array?
I can only push two values onto the stack array that I have created when I use the myPush() function.当我使用 myPush() 函数时,我只能将两个值推送到我创建的堆栈数组中。 The reason I need to do it this way is because I am not allowed to use the built-in stack functions.
我需要这样做的原因是因为我不允许使用内置的堆栈函数。 Plus I have to use an array not a lit.
另外我必须使用一个不点亮的阵列。 Thank you.
谢谢你。
I can only push two values onto the stack array that I have created when I use the myPush() function.当我使用 myPush() 函数时,我只能将两个值推送到我创建的堆栈数组中。 The reason I need to do it this way is because I am not allowed to use the built-in stack functions.
我需要这样做的原因是因为我不允许使用内置的堆栈函数。 Plus I have to use an array not a lit.
另外我必须使用一个不点亮的阵列。 Thank you.
谢谢你。
class Stack:
def __init__(self, data):
if data > 0:
self.stack = [0] * data
self.top = -1
self.stack[self.top] = self.stack[-1]
elif data <= 0:
self.stack = [0] * 10
self.top = -1
def showStack(self):
for i in self.stack:
print(i, end=" ")
return
def isEmpty(self):
return self.stack == []
def myEmpty(self): #complete this function
return # just a placeholder
def push(self, data):
self.stack.append(data)
def myPush(self, data):
if data == 0:
print("You did not enter a value.")
elif self.sizeStack() <= 10:
current = self.stack[stack.top]
self.stack[stack.top] = data
self.stack[stack.top - 1] = current
def pop(self):
data = self.stack[-1]
del self.stack[-1]
return data
def myPop(self): #complete this function
return # just a placeholder
def myPeek(self):
temp = self.top
return temp
def sizeStack(self):
return len(self.stack)
userVal = int(input("Enter the size of the stack: "))
stack = Stack(userVal)
while True:
print('\n1 display the stack')
print('2 add a value to the stack')
print('3 check the value at the top of the stack')
print('4 remove the value at the top of the stack')
print('5 check if the stack is empty')
print('99 quit')
option = int(input("Enter your choice: "))
if option == 1:
stack.showStack()
elif option == 2:
temp = int(input("Enter a number to add to the stack: "))
stack.myPush(temp)
elif option == 3:
print(stack.peek())
elif option == 99:
break
else:
print('Wrong option')
print
try defining a some customized functions that map to your list.尝试定义一些映射到您的列表的自定义函数。 Read up on customization here
在此处阅读自定义
class stack:
def __init__(self, data):
self.stack = [0] * data
self.top = -1
# whatever you want to do to init the list
def __str__(self): # replaces your showstack function now just use print(stack)
return self.stack
def __iter__(self): # creates an iterator you can use
return iter(self.stack)
def __len__(self): # replaces your sizestack function
return len(self.stack)
basically just adjust the methods you need.基本上只是调整你需要的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.