Python中的堆栈类

问题描述

我已经写了下面的代码来实现堆栈类,而不是使用内置函数,不确定我是否严格。有人可以帮我检查一下并告知是否有错误吗?

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函数了。到此为止。顺便说一句,在您的顶级函数中,您已经定义了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函数。 另外,尝试测试代码并解决所有问题。