在 Python 中堆叠 class

stack class in Python

我写了下面的代码来实现堆栈class而不是使用内置函数,不确定我是否理解正确。有人可以帮我检查一下,如果有错误请指教吗?

class DSAStack():

    maxCap = 100

    def __init__(self):
        self.stack = []

        self.count = 0


    def isEmpty(self):
        if self.count == 0:
            return True
        else:
            return false


    def isFull(self):
        if self.count == maxCap:
            return True
        else:
            return false


    def push(self, item):
        if self.isFull:
            raise ('Stack is full...')
        else:
            self.stack[self.count] = item
            self.count += 1


    def pop(self):
        self.topVal = self.top
        self.stack[self.count - 1] = 0
        self.count = self.count - 1

        return self.topVal


    def top(self):
        if self.isEmpty:
            raise ('Stack is empty...')
        else:
            self.top = self.stack[self.count - 1]

首先,您不需要记录计数。访问列表的长度将为您完成。

def __init__(self):
    self.stack =[]

现在,您的 isEmpty 和 isFull 逻辑没问题,但由于我们要删除 self.count 变量,下面是您的处理方式

def isEmpty(self):
    return len(self.stack) == 0 #Directly return true or false

def isFull(self):
    return len(self.stack) == maxCap #Directly return true or false

在您的推送功能中,有几点我想指出。 首先,您需要调用 isFull 函数。所以我们需要给它加上括号。

其次,你不能只raise ('Stack is full...'),你会得到一个TypeError: Exceptions must derive from BaseException。这基本上意味着你提出的一定是某种类型的错误。

最后,您不能通过 self.stack[self.count]=item 添加新元素,因为您会得到 IndexError

更改如下:

def push(self,item):
    if self.isFull():    #Need to call the function, self.isFull is not a variable
        raise Exception('Stack is full...') #Or any other type of error
    else:
        self.stack.append(item)    #Adds new item to the end of self.stack

现在来看 pop 函数,将列表中的值设置为零并不能真正消除它。它会引起很多混乱,特别是因为我们使用 len(self.stack) 来实现它。 以下是您的流行方式:

def pop(self):
    if self.isEmpty():
        raise Exception('Stack is empty...')
    else:
        return self.stack.pop() #List has a built-in pop method   

所以现在我们真的不需要 top 函数了。这就是结论。顺便说一句,在你的 top 函数中,你已经定义了 self.top = self.stack[self.count-1] 为函数和变量赋予相同的名称从来都不是一个好主意。

要自己实现弹出功能,您可以执行以下操作:

def pop(self):
    if self.isEmpty():
        raise Exception('Stack is empty...')
    else:
        topVal = self.stack[-1] #-1 gives you the last element
        #if stack will contain objects instead of primitive data types, use self.stack[-1].copy()
        del self.stack[-1] #Deletes the element
        return topVal

完善你的顶级功能将是这样的:

def top(self):
    if self.isEmpty():
        raise Exception('Stack is empty...')
    else:
        return self.stack[-1]
def pop(self):
    topVal = self.top()
    del self.stack[-1]    
    return topVal    

注意 top 函数是如何在 pop 函数之前定义的。 另外,尝试测试代码并解决任何问题。