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