python中的栈数据结构

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4688859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 16:56:43  来源:igfitidea点击:

Stack data structure in python

python

提问by Frankie Ribery

I have 2 issues with the code below:

我对下面的代码有两个问题:

  1. push(o) throws an exception TypeError: can only assign an iterable.
  2. Should I throw an exception if pop() is invoked on an empty stack ?

    class Stack(object):
    
        def __init__(self):
            self.storage = []
    
        def isEmpty(self):
            return len(self.storage) == 0
    
        def push(self,p):
            self.storage[:0] = p
    
        def pop(self):
            """issue: throw exception?"""
            return None
    
  1. push(o) 抛出异常TypeError: can only assignment an iterable
  2. 如果在空堆栈上调用 pop() ,我应该抛出异常吗?

    class Stack(object):
    
        def __init__(self):
            self.storage = []
    
        def isEmpty(self):
            return len(self.storage) == 0
    
        def push(self,p):
            self.storage[:0] = p
    
        def pop(self):
            """issue: throw exception?"""
            return None
    

采纳答案by Kimvais

No need to jump through these loops, See 5.1.1 Using Lists as Stacks

无需跳过这些循环,请参阅5.1.1 使用列表作为堆栈

If you insist on having methods isEmpty()and push()you can do:

如果你坚持有方法isEmpty()push()你可以这样做:

class stack(list):
    def push(self, item):
        self.append(item)
    def isEmpty(self):
        return not self

回答by Senthil Kumaran

Stack follows LIFO mechanism.You can create a list and do a normal append()to append the element to list and do pop()to retrieve the element out of the list which you just inserted.

堆栈遵循 LIFO 机制。您可以创建一个列表并执行常规append()操作将元素追加到列表中,并执行pop()从刚刚插入的列表中检索元素。

回答by Matt Fitzpatrick

I won't talk about the list structure as that's already been covered in this question. Instead I'll mention my preferred method for dealing with stacks:

我不会谈论列表结构,因为这个问题已经涵盖了。相反,我会提到我处理堆栈的首选方法:

I always use the Queuemodule. It supports FIFO and LIFO data structures and is thread safe.

我总是使用该Queue模块。它支持 FIFO 和 LIFO 数据结构并且是线程安全的。

See the docsfor more info. It doesn't implement a isEmpty()function, it instead raises a Fullor Emptyexception if a push or pop can't be done.

有关更多信息,请参阅文档。它不实现isEmpty()函数,而是在无法完成 push 或 pop 时引发FullorEmpty异常。

回答by Matthieu M.

You are right to use composition instead of inheritance, because inheritance brings methods in that you don't want to expose.

使用组合代替继承是正确的,因为继承带来了您不想公开的方法。

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

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

  def push(self,p):
    self.__storage.append(p)

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

This way your interface works pretty much like list(same behavior on popfor example), except that you've locked it to ensure nobody messes with the internals.

通过这种方式,您的界面的工作方式非常相似listpop例如,相同的行为),只是您已将其锁定以确保没有人弄乱内部结构。

回答by sumedhe

Here is an example for stack class

这是堆栈类的示例

class Stack(object):

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

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

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

   def peek(self):
       return self.items[-1]

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

回答by Lahiru Mirihagoda

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

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

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

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

        def size(self):
            return len(self.items)

        def peek(self):
            return self.items[-1]

Create a stack

创建堆栈

To create a new stack we can simply use Stack()

要创建一个新堆栈,我们可以简单地使用 Stack()

for example:

例如:

     s=Stack()

"s" is the name of new stack

“s”是新堆栈的名称

isEmpty

是空的

By using isEmpty()we can check our stack is empty or not

通过使用isEmpty()我们可以检查我们的堆栈是否为空

for example:

例如:

we have two stacks name s1=(0,1,4,5,6) and s2=()

我们有两个堆栈名称 s1=(0,1,4,5,6) 和 s2=()

if we use print(s1.isEmpty())it will return False

如果我们使用 print(s1.isEmpty())它会返回False

if we use print(s2.isEmpty())it will return True

如果我们使用 print(s2.isEmpty())它会返回True

push

By using push operation we can add items to top of the stack

通过使用推送操作,我们可以将项目添加到堆栈顶部

we can add "6" to the stack name "s" using

我们可以使用“6”添加到堆栈名称“s”

    s.push(6)

pop

流行音乐

we can use pop operation to remove and return the top item of a stack

我们可以使用 pop 操作移除并返回栈顶元素

if there is a stack name "s" with n amount items (n>0) we can remove it's top most item by using

如果有一个包含 n 个项目 (n>0) 的堆栈名称“s”,我们可以使用

    s.pop()

size

尺寸

This operation will return how many items are in the stack

此操作将返回堆栈中的项目数

if there is a stack name "s" s=(1,2,3,4,5,3)

如果有一个栈名 "s" s=(1,2,3,4,5,3)

    print(s.size())

will return "6"

将返回“6”

peekThis operation returns the top item without removing it

peek这个操作返回最上面的项目而不删除它

    print(s.peek())

"we can print items of the stack using print(s.items)"

“我们可以使用print(s.items)”打印堆栈中的项目

回答by krezaeim

class Stack:
    def __init__(self):
        self.stack = []
    def pop(self):
        if self.is_empty():
            return None
        else:
            return self.stack.pop()
    def push(self, d):
        return self.stack.append(d)
    def peek(self):
        if self.is_empty():
            return None
        else:
            return self.stack[-1]
    def size(self):
        return len(self.stack)
    def is_empty(self):
        return self.size() == 0