用Python实现堆栈

时间:2013-08-16 18:20:57

标签: python algorithm data-structures stack

我正在尝试使用数组实现Python的简单堆栈。我想知道是否有人能让我知道我的代码有什么问题。

class myStack:
     def __init__(self):
         self = []

     def isEmpty(self):
         return self == []

     def push(self, item):
         self.append(item)

     def pop(self):
         return self.pop(0)

     def size(self):
         return len(self)

    s = myStack()
    s.push('1')
    s.push('2')
    print(s.pop())
    print s

12 个答案:

答案 0 :(得分:12)

我在下面纠正了一些问题。此外,抽象编程术语中的“堆栈”通常是一个集合,您可以在其中添加和删除顶部,但是实现它的方式,您将添加到顶部并从底部删除,这使其成为一个队列

class myStack:
     def __init__(self):
         self.container = []  # You don't want to assign [] to self - when you do that, you're just assigning to a new local variable called `self`.  You want your stack to *have* a list, not *be* a list.

     def isEmpty(self):
         return self.size() == 0   # While there's nothing wrong with self.container == [], there is a builtin function for that purpose, so we may as well use it.  And while we're at it, it's often nice to use your own internal functions, so behavior is more consistent.

     def push(self, item):
         self.container.append(item)  # appending to the *container*, not the instance itself.

     def pop(self):
         return self.container.pop()  # pop from the container, this was fixed from the old version which was wrong

     def peek(self):
         if self.isEmpty():
             raise Exception("Stack empty!")
         return self.container[-1]  # View element at top of the stack

     def size(self):
         return len(self.container)  # length of the container

     def show(self):
         return self.container  # display the entire stack as list


s = myStack()
s.push('1')
s.push('2')
print(s.pop())
print(s.show())

答案 1 :(得分:4)

分配给self不会将您的对象转换为列表(如果确实如此,则该对象将不再具有所有堆栈方法)。分配给self只会更改局部变量。而是设置一个属性:

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

并使用该属性而不仅仅是裸self

def push(self, item):
    self.stack.append(item)

此外,如果您想要一个堆栈,则需要pop()而不是pop(0)pop(0)会将您的数据结构转换为(效率低下的)队列。

答案 2 :(得分:2)

我发表了评论,其中包含指向http://docs.python.org/2/tutorial/datastructures.html#using-lists-as-stacks的链接,但是如果您希望自定义类型为您提供pushpopis_empty和{{方便的方法,我只是子类size

list

但是,正如我在评论中所说的那样,我可能只是坚持使用class Stack(list): def push(self, item): self.append(item) def size(self): return len(self) def is_empty(self): return not self ,因为您所做的只是对现有方法进行别名处理,这通常只会使您的代码难以使用从长远来看,因为它需要人们使用它来学习原始的别名界面。

答案 3 :(得分:1)

正确的实现还包括__iter__,因为Stack需要是LIFO命令。

class Stack:
    def __init__(self):
        self._a = []

    def push(self, item):
        self._a.append(item)

    def pop(self):
        return self._a.pop()

    def isEmpty(self):
        return len(self._a) == 0

    def __iter__(self):
        return reversed(self._a)

    def __str__(self):
        # return str(list(reversed(self._a)))
        return str(list(iter(self)))

def main():
    stack = Stack()
    stack.push('a')
    stack.push('b')
    stack.push('c')
    stack.pop()
    print(stack)
    if stack:
        print("stack not empty")
    stack.pop()
    stack.pop()
    if stack.isEmpty():
        print("stack empty")

if __name__ == '__main__':
    main()

答案 4 :(得分:1)

堆栈是一个容器(线性集合),其中动态设置操作 按照后进先出(LIFO)原则进行。 只有一个指针-top,用于执行这些操作

使用数组的堆栈的CLRS实现:

class Stack:
    """
    Last in first out (LIFO) stack implemented using array.
    """
    def __init__(self, capacity=4):
        """
        Initialize an empty stack array with default capacity of 4.
        """
        self.data = [None] * capacity
        self.capacity = capacity
        self.top  = -1

    def is_empty(self):
        """
        Return true if the size of stack is zero.
        """
        if self.top == -1:
            return True
        return False

    def push(self, element):
        """
        Add element to the top.
        """
        self.top += 1
        if self.top >= self.capacity:
            raise IndexError('Stack overflow!')
        else:
            self.data[self.top] = element

    def pop(self):
        """
        Return and remove element from the top.
        """
        if self.is_empty():
            raise Exception('Stack underflow!')
        else:
            stack_top = self.data[self.top]
            self.top -= 1
            return stack_top

    def peek(self):
        """
        Return element at the top.
        """
        if self.is_empty():
            raise Exception('Stack is empty.')
            return None
        return self.data[self.top]

    def size(self):
        """
        Return the number of items present.
        """
        return self.top + 1

测试实现:

def main():
    """
    Sanity test
    """
    stack = Stack()

    print('Size of the stack is:', stack.size())
    stack.push(3)
    print('Element at the top of the stack is: ', stack.peek())
    stack.push(901)
    print('Element at the top of the stack is: ', stack.peek())
    stack.push(43)
    print('Element at the top of the stack is: ', stack.peek())
    print('Size of the stack is:', stack.size())
    stack.push(89)
    print('Element at the top of the stack is: ', stack.peek())
    print('Size of the stack is:', stack.size())
    #stack.push(9)    # Raises IndexError
    stack.pop()
    print('Size of the stack is:', stack.size())
    stack.pop()
    print('Size of the stack is:', stack.size())
    stack.pop()
    print('Size of the stack is:', stack.size())
    print('Element at the top of the stack is: ', stack.peek())
    stack.pop()
    #print('Element at the top of the stack is: ', stack.peek())    # Raises empty stack exception

if __name__ == '__main__':
    main()

答案 5 :(得分:0)

您的问题是,当您从列表末尾弹出时,您将从列表的开头弹出。堆栈是一个Last-In First-Out数据结构,这意味着当你从中弹出一些东西时,那些东西将是你最后推送的东西。看看你的推送功能 - 它将一个项目附加到列表中。这意味着它位于列表的末尾。但是,当您调用.pop(0)时,您将删除列表中的第一个项目,而不是上次附加的项目。从.pop(0)中删除0应该可以解决您的问题。

答案 6 :(得分:0)

你的堆栈是一个数组...

class stacked(): # Nodes in the stack
    def __init__(self,obj,next):
        self.obj = obj
        self.next = next
    def getObj(self):
        return(self.obj)
    def getNext(self):
        return(self.next)

class stack(): # The stack itself
    def __init__(self):
        self.top=None
    def push(self,obj):
        self.top = stacked(obj,self.top)
    def pop(self):
        if(self.top == None):
            return(None)
        r = self.top.getObj()
        self.top = self.top.getNext()
        return(r)

答案 7 :(得分:0)

下面是python中堆栈的简单实现。此外,它会在任何时间点返回中间元素。

  class Stack:
        def __init__(self):
            self.arrList = []

        def isEmpty(self):
            if len(self.arrList):
                return False
            else:
                return True

        def push(self, val):
            self.arrList.append(val)

        def pop(self):
            if not self.isEmpty():
                self.arrList[len(self.arrList)-1]
                self.arrList = self.arrList[:len(self.arrList)-1]
            else:
                print "Stack is empty"

        def returnMiddle(self):
            if not self.isEmpty():
                mid = len(self.arrList)/2
                return self.arrList[mid]
            else:
                print "Stack is empty"

        def listStack(self):
            print self.arrList

    s = Stack()
    s.push(5)
    s.push(6)
    s.listStack()
    print s.returnMiddle()
    s.pop()
    s.listStack()
    s.push(20)
    s.push(45)
    s.push(435)
    s.push(35)
    s.listStack()
    print s.returnMiddle()
    s.pop()
    s.listStack()

输出:

[5, 6]
6
[5]
[5, 20, 45, 435, 35]
45
[5, 20, 45, 435]

答案 8 :(得分:0)

来自“算法和数据结构的问题解决”一书中的

Implementing a Stack in Python

答案 9 :(得分:0)

下面是我的实现

class Stack:
    def __init__(self):
        self.items = list()
    def is_empty(self):
        return self.items == []
    def peek(self):
        if self.is_empty():
            print('Cannot peek empty stack')
            return
        else:
            return self.items[-1]
    def pop(self):
        if self.is_empty():
            print('Cannot pop an empty stack')
            return
        else:
            return self.items.pop()
    def size(self):
        return len(self.items)
    def push(self,data):
        self.items.append(data)

答案 10 :(得分:0)

我想分享继承Python列表的堆栈实现版本。我相信堆栈上的迭代应该按照LIFO顺序进行。此外,在弹出所有元素时,应提供pop-all()上的迭代以进行迭代。我还添加了stack.clear()来清空堆栈(就像在collections模块中的deque.clear()中一样)。我还重写了__repr__用于调试:

class Stack(list):

    def push(self, item):
        self.append(item)

    def top(self):
        return self[-1]

    def size(self):
        return len(self)

    def isempty(self):
        return self.size() == 0

    def __iter__(self):
        """ iter in lifo """
        return super(Stack, self).__reversed__()

    def __reversed__(self):
        return super(Stack, self).__iter__()

    def popall(self):
        try:
            while True:
                yield self.pop()
        except IndexError:
            pass

    def clear(self):
        del self[:]

    def __repr__(self):
        if not self:
            return '%s()' % self.__class__.__name__
        return '%s(%s)' % (self.__class__.__name__, super(Stack, self).__repr__())

这里是使用方式:

stack = Stack(range(5))
print "stack: ", stack  # stack:  Stack([0, 1, 2, 3, 4])

print "stack.pop() => ", stack.pop() # stack.pop() =>  4
print "stack.push(20) " # stack.push(20) 
stack.push(20)
for item in stack:
    print item  # prints 20, 3, 2... in newline
print "stack: ", stack # stack:  Stack([0, 1, 2, 3, 20])
print "stack pop all..."
for item in stack.popall(): # side effect to clear stack
    print item
print "stack: ", stack # stack:  Stack()

主要,我实现了它来解决编程问题next greater element

答案 11 :(得分:-2)

class Stack:
   s =[]

   def push(self, num):
       self.s.append(num)

   def pop(self):
       if len(self.s) == 0: # erro if you pop an empty list
           return -1
       self.s.remove(self.s[-1])

   def isEmpty(self):
       if len(self.s) == 0:
           return True
       else:
           return False

   def display(self): # this is to display how a stack actually looks like
       if self.isEmpty():
           print("Stack is Empty")
    
       for i in range(len(self.s)-1,-1,-1): # I haven't used reversed() since it will be obv
           print(self.s[i])


obj = Stack()
obj.push(3)
print(obj.isEmpty())
obj.push(4)
obj.display()
print("----")
obj.pop()
obj.display()