使用myPush()函数时,我只能将两个值压入创建的堆栈数组中。之所以需要这样做,是因为不允许使用内置的堆栈函数。另外,我必须使用不亮的数组。谢谢。
使用myPush()函数时,我只能将两个值压入创建的堆栈数组中。之所以需要这样做,是因为不允许使用内置的堆栈函数。另外,我必须使用不亮的数组。谢谢。
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
答案 0 :(得分:0)
尝试定义一些映射到您的列表的自定义函数。在customization上阅读
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)
基本上只是调整所需的方法。