用列表构建栈结构

5.1 问题

创建stack.py脚本,要求如下:

  1. 栈是一个后进先出的结构
  2. 编写一个程序,用列表实现栈结构
  3. 需要支持压栈、出栈、查询功能
    #!/usr/local/bin/python3
    # -*- conding : utf-8 -*-
    """
    @Time         :  19-3-16 上午9:10
    @Author       :  xq
    @Software     :  PyCharm
    @File         :  stack.py.py
    @Description   :
    """
    
    stack = []
    
    def push_it():
        item = input('item to push: ').strip()
        if item:
            stack.append(item)
    def pop_it():
        if stack:
            print('From stack,poped',stack.pop())
    
    
    def view_it():
         print(stack)
    
    def show_menu():
        cmd = {'0':push_it,'1':pop_it,'2':view_it}  #把函数存入字典,去函数 不是调用函数
        prompt = """(0) push it
    (1)pop it
    (2)view it
    (3)quit
    please input your choice(0/1/2/3):"""
        while True:
            choice = input(prompt).strip()  #去除用户输入的两端的空白字符
            if choice not in['0','1','2','3']:
               print("Invalid input,please try again")
               continue
            if choice == '3':
                break
            cmd[choice]()
    
            # if choice == '0':
            #     push_it()
            # elif choice == '1':
            #     pop_it()
            # elif choice == '2':
            #     view_it()
            # else:
            #     break
    
    
    if __name__ == "__main__":
         show_menu()

猜你喜欢

转载自www.cnblogs.com/lsgo/p/10544680.html