Python堆栈

时间:2020-02-23 14:43:21  来源:igfitidea点击:

在上一教程中,我们了解了Python信号处理。
在本教程中,我们将学习python堆栈。

Python堆栈

要开始本教程,您首先必须知道什么是堆栈。
基本上,堆栈是后进先出数据结构。
这意味着,系统中最后输入的项目将首先被删除。

例如,假设您的管道只有一个开口端。
而且您有一些球恰好适合管道。
因此,当您将这些球插入管道时,它们会相互堆叠。
但是,当您将球卸下时,最后一个将被首先卸下。

Python Stack推送

好吧,没有像python堆栈那样的其他数据结构。
但是由于堆栈是非常常见的数据结构,因此我们将尝试实现该结构。

因此,如果您已经学习过堆栈,则应该知道堆栈有两个操作。
一个是" push",另一个是" pop"。
在本节中,我们将讨论推送操作。
推送操作用于将项目添加到堆栈中。
因为我们将使用Python List作为堆栈,所以我们可以使用append()函数将项目推入列表。

stack = []  # initialize a list as stack
print('current stack :', stack)

# add items to the stack
for i in range(5):
  # push items into stack
  stack.append(i)
  print('current stack :', stack,'\tstack size :', len(stack))

Python堆栈弹出

现在我们需要学习如何从堆栈中弹出项目。
Python List有一个名为pop()的函数,该函数从列表中删除最后一个元素。
但是在删除之前,您必须检查堆栈是否为空。
因此,如果我们在先前的代码中添加pop实现,那么最终的代码将如下所示。

stack = []  # initialize a list as stack
print('\ncurrent stack :', stack)

print('\nPush items to the stack')
# add items to the stack
for i in range(5):
  # push items into stack
  stack.append(i)
  print('current stack :', stack,'\tstack size :', len(stack))

print('\nPop items from te stack')
# now pop items from the stack
while len(stack) > 0:  # check if the stack is empty
  stack.pop()
  print('current stack :', stack, '\tstack size :', len(stack))

因此,输出将如下所示。

Push items to the stack
current stack : [0]     stack size : 1
current stack : [0, 1]     stack size : 2
current stack : [0, 1, 2]     stack size : 3
current stack : [0, 1, 2, 3]     stack size : 4
current stack : [0, 1, 2, 3, 4]     stack size : 5

Pop items from te stack
current stack : [0, 1, 2, 3]     stack size : 4
current stack : [0, 1, 2]     stack size : 3
current stack : [0, 1]     stack size : 2
current stack : [0]     stack size : 1
current stack : []     stack size : 0

Python Stack实施

如您所见,我们可以利用List append()和pop()函数创建我们的Stack实现类。
这是一个带有示例的Stack实现类。

class Stack:
  stack = []  # empty list
  max_size = -1

  def __init__(self, size=-1):  # defining maximum size in the constructor
      self.max_size = size

  def push(self, item):
      if self.max_size == -1:  # if there is no limit in stack
          self.stack.append(item)
      elif len(self.stack) < self.max_size:  # if max limit not crossed
          self.stack.append(item)
      else:  # if max limit crossed
          print('Can\'t add item. Stack limit is :', self.max_size)
          raise RuntimeError

  def pop(self):
      if len(self.stack) > 0:
          temp = self.stack[-1]
          self.stack.pop()
          return temp
      else:
          print('stack is already empty.')
          raise IndexError

  def top(self):
      if len(self.stack) > 0:
          return self.stack[-1]  # returns the last item
      else:
          print('stack is already empty.')
          raise IndexError

stack = Stack()
stack.push(1)  # push item 1
stack.push(2)  # push item 2
print('Pop the last item :', stack.pop())  # pop the top item
print('Current top item is :', stack.top())  # current top item

上面的代码将这样输出

Pop the last item : 2
Current top item is : 1