Python如何用列表构建栈结构

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

栈是一个后进先出的结构
编写一个程序,用列表实现栈结构
需要支持压栈、出栈、查询功能
1.2 方案
创建空列表存储数据,创建4个函数,分别实现压栈、出栈、查询以及判断函数调用的方法。

此程序需要注意的是堆栈的结构特点,先进后出,后进先出:

1.调用show_menu()函数后,利用while循环交互端输出提示,请用户input0/1/2/3任意数值,如果输入的值不是0/1/2/3,打印输入值无效请重新输入并重新开始循环,如果输入的值是3,停止整个循环,如果输入的值是0/1/2通过字典键值对关联关系,调用相对应函数

2.如果输入的值是0,字典cmds中0键对应的值是push_it,push_it()调用压栈函数,压栈函数利用stack.append()方法将输入数据追加到列表结尾

3.如上,如果输入的值是1,调用出栈函数pop_it(),出栈函数如果stack列表中有数据,弹出列表最后一个元素(根据堆栈结构特点stack.pop()中参数为空),如果stack列表没有数据,输出空列表

4.如果输入的值是2,调用查询函数view_it(),显示当前列表

1.3 步骤
实现此案例需要按照如下步骤进行。

步骤一:编写脚本

让输出的文字带颜色:\033[31;1m高亮度红色字体、\033[31;1m高亮度绿色字体、\033[0m关闭所有属性

[root@localhost day04]# vim stack.py
#!/usr/bin/env python3
stack = []
def push_it():
    item = input('item to push: ')
    stack.append(item)
def pop_it():
    if stack:   
        print("\033[31;1mPopped %s\033[0m" % stack.pop())
    else:
        print('\033[31;1mEmpty stack\033[0m')
def view_it():
    print("\033[32;1m%s\033[0m" % stack)
def show_menu():
    prompt = """(0) push_it
(1) pop_it
(2) view_it
(3) quit
Please input your choice(0/1/2/3): """
    cmds = {'0': push_it, '1': pop_it, '2': view_it}
    while True:
        # strip() 方法用于移除字符串头尾指定的字符(默认为空格)
        choice = input(prompt).strip()[0]    
        if choice not in '0123':
            print('Invalid input. Try again.')
            continue     #结束本次循环
    
        if choice == '3':
            break       #结束整个循环
   
        cmds[choice]()   # push_it()  pop_it()
        # if choice == '0':
        #     push_it()
        # elif choice == '1':
        #     pop_it()
        # elif choice == '2':
        #     view_it()
if __name__ == '__main__':
    show_menu()

步骤二:测试脚本执行

[root@localhost day04]# python3 stack.py
(0) push_it
(1) pop_it
(2) view_it
(3) quit
Please input your choice(0/1/2/3): 6
Invalid input. Try again.
(0) push_it
(1) pop_it
(2) view_it
(3) quit 
Please input your choice(0/1/2/3): 0
item to push: nihao
(0) push_it
(1) pop_it
(2) view_it
(3) quit
Please input your choice(0/1/2/3): 1 
Popped nihao
(0) push_it
(1) pop_it
(2) view_it
(3) quit
Please input your choice(0/1/2/3): 2
[]
(0) push_it
(1) pop_it
(2) view_it
(3) quit
Please input your choice(0/1/2/3): 0
item to push: a         
(0) push_it
(1) pop_it
(2) view_it 
Please input your choice(0/1/2/3): 0
item to push: b
(0) push_it
(1) pop_it
(2) view_it
(3) quit
Please input your choice(0/1/2/3): 0
item to push: c
(0) push_it
(1) pop_it
(2) view_it
(3) quit
Please input your choice(0/1/2/3): 1
Popped c
(0) push_it
(1) pop_it
(2) view_it
(3) quit
Please input your choice(0/1/2/3): 2
['a', 'b']
(0) push_it
(1) pop_it
(2) view_it
(3) quit
Please input your choice(0/1/2/3): 3
(3) quit
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章