Home  >  Article  >  Backend Development  >  Python data structure stack example code

Python data structure stack example code

高洛峰
高洛峰Original
2017-02-07 13:02:021239browse

Python stack

The stack is a last-in-first-out (LIFO) data structure. The stack data structure can be used to handle most program flows with LIFO characteristics.
In the stack , push and pop are common terms:

push: means pushing an object onto the stack.

pop: means popping an object out of the stack.

The following is a Simple stack structure implemented in Python:

stack = []         # 初始化一个列表数据类型对象, 作为一个栈
 
def pushit():       # 定义一个入栈方法
  stack.append(raw_input('Enter New String: ').strip())   
  # 提示输入一个入栈的 String 对象, 调用 Str.strip() 保证输入的 String 值不包含多余的空格
 
def popit():        # 定义一个出栈方法
  if len(stack) == 0:
    print "Cannot pop from an empty stack!"
  else:
    print 'Remove [', `stack.pop()`, ']'
    # 使用反单引号(` `)来代替 repr(), 把 String 的值用引号扩起来, 而不仅显示 String 的值
 
def viewstack():      # 定义一个显示堆栈中的内容的方法
    print stack
 
CMDs = {'u':pushit, 'o':popit, 'v':viewstack}
# 定义一个 Dict 类型对象, 将字符映射到相应的 function .可以通过输入字符来执行相应的操作
 
def showmenu():      # 定义一个操作菜单提示方法
  pr = """
  p(U)sh
  p(O)p
  (V)iew
  (Q)uit
 
  Enter choice: """
 
  while True:
    while True:
      try:
        choice = raw_input(pr).strip()[0].lower()
        # Str.strip() 去除 String 对象前后的多余空格
        # Str.lower() 将多有输入转化为小写, 便于后期的统一判断
        # 输入 ^D(EOF, 产生一个 EOFError 异常)
        # 输入 ^C(中断退出, 产生一个 keyboardInterrupt 异常)
 
      except (EOFError, KeyboardInterrupt, IndexError):
        choice = 'q'
 
      print '\nYou picked: [%s]' % choice
 
      if choice not in 'uovq':
        print 'Invalid option, try again'
      else:
        break
 
 
    if choice == 'q':
      break
    CMDs[choice]()
    # 获取 Dict 中字符对应的 functionName, 实现函数调用
 
if __name__ == '__main__':
  showmenu()

NOTE: In the stack data structure, the container and mutability characteristics of the List data type object are mainly used, as shown in List.append() and List.pop( ) Calling of the built-in functions of these two list types.

Thanks for reading, I hope it can help everyone, thank you for your support of this site!

For more articles related to Python data structure stack example code, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn