在python中使用numpy实现堆栈



就像c++中有使用数组实现堆栈一样,我想知道是否也可以在使用numpy堆栈的python中实现同样的功能?这是我对的看法

from turtle import shape
import numpy as np

class stack:
def __init__(self):
self.stack = np.empty(shape=(1,100),like=np.empty_like)
self.n = 100
self.top = -1
def push(self, element):
if (self.top >= self.n - 1):
print("Stack overflow")
else:
self.top = self.top + 1
self.stack[self.top] = element
def pop(self):
if (self.top <= -1):
print("Stack Underflow")
else:
print("Popped element: ", self.stack[self.top])
self.top = self.top - 1
def display(self):
if (self.top >= 0):
print("Stack elements are: ")
i = self.top
while i >= 0:
print(self.stack[i], end=", ")
i = i - 1
else:
print("The stack is empty")
def gettop(self):
if (self.top <= -1):
print("Empty stack")
else:
print("Top: ", self.stack[self.top])
def isEmpty(self):
if (self.top == -1):
print("Stack is Empty")
else:
print("Stack is not empty")

if __name__ == "__main__":
s = stack()
ch = 0
val = 0
print("1) Push in stack")
print("2) Pop from stack")
print("3) Get Top")
print("4) Check if Empty")
print("5) Display Stack")
print("6) Exit")
while (ch != 6):
ch = int(input("Enter Choice: "))
print(ch)
if (ch == 1):
val = input("Enter the value to be pushed: ")
s.push(val)
elif (ch == 2):
s.pop()
elif (ch == 3):
s.gettop()
elif (ch == 4):
s.isEmpty()
elif (ch == 5):
s.display()
elif (ch == 6):
print("Exit")
else:
print("Invalid Choice")

但我一开始就被堆栈的创建卡住了。当我试图将任何元素推入数组时,它会生成一个满12的堆栈。

我确实知道在python中有更简单的实现,但我很好奇这是否可能。

我把代码搞了一段时间,找到了一种方法,现在是:

"""
Time: 15:08
Date: 16-02-2022
"""
from turtle import shape
import numpy as np

class stack:
def __init__(self):
self.stack = np.array([0,0,0,0,0,0,0,0,0,0])
self.n = 10
self.top = -1
def push(self, element):
if (self.top >= self.n - 1):
print("Stack overflow")
else:
self.top = self.top + 1
self.stack[self.top] = element
def pop(self):
if (self.top <= -1):
print("Stack Underflow")
else:
print("Popped element: ", self.stack[self.top])
self.top = self.top - 1
def display(self):
if (self.top >= 0):
print("Stack elements are: ")
i = self.top
while i >= 0:
print(self.stack[i], end=", ")
i = i - 1
print("")
else:
print("The stack is empty")
def gettop(self):
if (self.top <= -1):
print("Empty stack")
else:
print("Top: ", self.stack[self.top])
def isEmpty(self):
if (self.top == -1):
print("Stack is Empty")
else:
print("Stack is not empty")

if __name__ == "__main__":
s = stack()
ch = 0
val = 0
print("1) Push in stack")
print("2) Pop from stack")
print("3) Get Top")
print("4) Check if Empty")
print("5) Display Stack")
print("6) Exit")
while (ch != 6):
ch = int(input("Enter Choice: "))
print(ch)
if (ch == 1):
val = input("Enter the value to be pushed: ")
s.push(val)
elif (ch == 2):
s.pop()
elif (ch == 3):
s.gettop()
elif (ch == 4):
s.isEmpty()
elif (ch == 5):
s.display()
elif (ch == 6):
print("Exit")
else:
print("Invalid Choice")

最新更新